Platinum Partner

Radix Conversion In C

// 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.

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;
}
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}