Return to Snippet

Revision: 61184
at December 2, 2012 12:45 by rtperson


Initial Code
char* convertFromDecimal(int num, int toBase) {
    char chars[] = { "0123456789ABCDEFGHIJ" };
    char *result;
    char digit[] = { '\0', '\0' };
    char temp[RESERVE_CHARS];
    memset(temp, 0, sizeof temp);
    result = (char*)calloc(RESERVE_CHARS, sizeof(char));
    memset(result, 0, sizeof result);
    
    int over;
    while (num > 0) {
        over = num % toBase;
        digit[0] = chars[over];
        strcat(temp, digit);
        num /= toBase;
    }
    
    /* reverse the temp string to get real digit */
    int p, x;
    for ( p = strlen(temp)-1, x=0; p >= 0; --p, ++x) {
        result[x] = temp[p];
    }
    
    return result;
}

Initial URL

                                

Initial Description
How to convert an integer from base 10 to a string of base x (where x <= 20). The #define RESERVE_CHARS should be set to the largest size for the resulting string. Or feel free to adjust the code to reallocate storage for the string.

Initial Title
Radix Conversion In C

Initial Tags

                                

Initial Language
C