Converting a Positive Integer to Another Base - C Function

C examples for Function:Utility Function

Description

Converting a Positive Integer to Another Base

Demo Code

#include <stdio.h>

int convertedNumber[64];
long int numberToConvert = 123;
int base = 2;// www .jav a2 s.c  o  m
int digit = 0;

void convertNumber (void){
    do{
        convertedNumber[digit] = numberToConvert % base;
        ++digit;
        numberToConvert /= base;
    } while (numberToConvert != 0);
}

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

    printf ("Converted number = ");

    for ( --digit; digit >= 0; --digit )
    {
        nextDigit = convertedNumber[digit];
        printf ("%c", baseDigits[nextDigit]);
    }

    printf ("\n");
}

int main (void)
{
    convertNumber ();
    displayConvertedNumber ();

    return 0;
}

Related Tutorials