0

I wrote a function in C that convert a binary number to a decimal one:

while (n != '\n')
{
    scanf("%c",&n);
    if (n == '1')
        var = var * 2 + 1;
    else if (n == '0')
        var *= 2;
}

Now I wonder how to put each number of the decimal in an array of char.

Ex: var=145 is the converted number, so the array should be like this:

char array[n_bit]={1,4,5};
Jonas
  • 6,915
  • 8
  • 35
  • 53
Alopex
  • 131
  • 1
  • 1
  • 8

1 Answers1

0

This should do what you need (at least as I understood it):

// returns the number of decimal digits in 'num'
unsigned int getNumDigits(unsigned int num)
{
    unsigned int res = 1; // when the 'num' is 0, the number of digits is 1
    num /= 10; 

    while (num)
    {
       res++;
       num /= 10;
    }

    return res;
}

// fill the 'array' with chars which represent the digits in the given 'inputNum'
// so that if inputNum=135, array[0]='1', array[1]='3' and array[2]='5'
// assuming 'array' contains nothing but '\0's when given as input
int fillDecimalVector(unsigned int inputNum, char array[], size_t arr_size)
{
   unsigned int fillIdx = 0;
   unsigned int numOfDigits = getNumOfDigits(inputNum);

   if (numOfDigits > arrSize)
       return -1;

   // when the 'inputNum' initial value is 0 we are expected to fill '0'
   while (inputNum || !fillIdx)
   {
       array[numOfDigits - fillIdx - 1] = '0' + (char)(inputNum % 10);
       fillIdx++;
       inputNum /= 10;
   }

   return 0;
}

NOTE

I didn't try to compile it so there might be minor syntax errors.

Alex Lop.
  • 6,810
  • 1
  • 26
  • 45