Over a million developers have joined DZone.

Radix Conversion In C

DZone's Guide to

Radix Conversion In C

Free Resource
// 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;

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}