Luke Collins Luke Collins - 13 days ago 5
C Question

Changing an unsigned decimal to base 2^n

For a programming assignment, I need to code a function

to_base(n,x)
in C which takes an input
x
and converts it to base
n
, where
x
is a decimal number and
n
can be expressed as
2^y
. Does anyone have any idea how to go about this?

I managed to code a function which changes to binary using recursive division, but I don't know how to generalise it.

void to_base(unsigned long x, int n)
{
int r;
r = x%2;
if(x != 0)
to_base_n(x/2,n);
printf("%c",(r == 0 ? '0' : '1'));
}

Answer

I've done something similar while studying C with Kochan manual and in chapter 7 I had to solve a problem like yours, so I came up with this solution:

// Program to convert a positive integer to another base

#include <stdio.h>
#include <stdbool.h>

int       convertedNumber[64];
long int  numberToConvert;
int       base;
int       digit;

void  getNumberAndBase (void)
{
    bool askAgain = true;

    printf ("Number to be converted? ");
    scanf ("%li", &numberToConvert);

    if (numberToConvert == 0)
    {
        askAgain = false;
    }

    while (askAgain)
    {
        printf ("Base? ");
        scanf ("%i", &base);        
        if  ( base < 2  ||  base > 16 ) {
            printf ("Bad base - must be between 2 and 16\n");
        } else {
            askAgain = false;
        }
    };

}

void  convertNumber (void)
{
    digit = 0;
    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)
{
    void  getNumberAndBase (void), convertNumber (void),
          displayConvertedNumber (void);

    while (true)
    {
        getNumberAndBase ();

        if (numberToConvert == 0)
        {
            break;
        }
        convertNumber ();
        displayConvertedNumber ();
    }
    return 0;
}

Actually you don't need a recursive function, a while loop like the one in convertNumber function will do, you have to divide until there's nothing left.

The example I post is simple with no function arguments but global variables because that was the level on that chapter of the book but I think that will give you a good direction that you can elaborate further

Comments