Home > Software design >  Stuck in decimal to binary using C
Stuck in decimal to binary using C

Time:09-17

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

CodePudding user response:

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.

CodePudding user response:

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!

CodePudding user response:

As explained in the comments, this is not a conversion. Here is a function that returns a string representing the binary display of the given #: #include <stdio.h> #include <string.h>

char *dtob(int n, char *ans){ char ANS[33] = { '0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','\0'}; int i = 31;

while(n>=1){
    if(n*(n%2)){
        ANS[i] = '1';
    }
    n=n/2;
    i--;
}
strcpy(ans, ANS);

return(ans);

}

int main(void){ char ans[33];

for(int i = 0; i <= 16; i  ){
      printf("%s\n", dtob(i, ans));
}

return(0);

}

CodePudding user response:

I tested your code and it works for me, maybe you messed up something in main or somewhere else. Also I recommend to use string instead of int because for numbers larger than 1023 you will exceed the limit for int type and with string you can convert any number you want.

  • Related