Stuck in decimal to binary using C

94 Views Asked by At

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??

2

There are 2 best solutions below

0
Lundin On BEST ANSWER

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.

5
Sharvansh Shukla On

This seems to be a compiler issue, as the code works fine on online IDEs. I will be closing the question now. Thanks for the input.

Edit: The issue actually seemed to be due to pow giving a 99.9999-ish value for 10^2 and such, which is why it was truncated and gave an offset result. A simple addition to the code did it for me:

bin += round(pow(10,i))*(n%2);

Thank you for all the input, once again!