cnumber-systems

Stuck in decimal to binary using C


Below is a function I created to convert a decimal number to binary:

int dtob(int n)
{
    int bin = 0;
    int i=0;
    while(n>=1)
    {
        bin += pow(10,i)*(n%2);
        n=n/2;
        i++;
    }
    return bin;
}

Now this function gives correct binary value for some inputs such as 0 through 3 and then 8 through 11, but gives an incorrect input offset by 1, when dealing with inputs like 4,5,6,12 etc.

Incorrect output

Correct Output

Could someone tell me what flaw there is in the logic that I have used??


Solution

  • I think what you are actually looking for is a version without floating point functions like pow(). Something like this:

    #include <stdio.h>
    #include <stdint.h>
    
    uint32_t bin_to_wannabe_bin (uint32_t bin)
    {
      uint32_t result=0;
    
      for(size_t i=0; i<32; i++)
      {
        result *= 10;
        result |= (bin >> (31-i)) & 1u;
      }
      return result;
    }
    
    int main (void)
    {
      printf("%u\n", bin_to_wannabe_bin(10));
      printf("%u\n", bin_to_wannabe_bin(123));
    }
    

    Output:

    1010
    1111011
    

    Please note that this holds no error handling so it will easily overflow when you run out of the 10 decimal digits of a 32 bit int.