Convert a positive integer to another base. - C Data Type

C examples for Data Type:int

Description

Convert a positive integer to another base.

Demo Code

#include <stdio.h>

int main (void)
{
    const char baseDigits[16] = {
            '0', '1', '2', '3', '4','5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    int convertedNumber[64];

    int numberToConvert;

    int nextDigit, base, index = 0;

    printf ("Number:");
    scanf ("%d", &numberToConvert);
    printf ("Base: ");
    scanf ("%d", &base);

    do {//from   w w  w .  j a va 2  s.com
        convertedNumber[index] = numberToConvert % base;
    
        ++index;
    
        numberToConvert = numberToConvert / base;
    } while (numberToConvert != 0);

    printf ("Converted number = ");
    
    for(--index; index >= 0; --index) {
    
        nextDigit = convertedNumber[index];
    
        printf ("%c", baseDigits[nextDigit]);
    }
    printf ("\n");

    return 0;
}

Related Tutorials