DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Roger has posted 34 posts at DZone. View Full User Profile

Radix Conversion In C

12.08.2008
| 4454 views |
  • submit to reddit
        // 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;
}