Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal to binary algorithm in C

I am trying to use the following algorithm to convert a decimal number to a binary number in C. I don't understand why it doesn't work properly for some inputs (e.g. for 1993 I get 1420076519).

int aux=x;
long bin=0;
while (aux>0)
{
    bin=bin*10+aux%2;
    aux=aux/2;
}
printf("%d in decimal is %ld in binary.", x, bin);
like image 331
Tudor Ciotlos Avatar asked Nov 02 '12 18:11

Tudor Ciotlos


1 Answers

When you print a long you dont print the binary. The best way to convert to binary or show the binary representation of a decimal number is by storing it in a string. Bellow is a solution offered in a another SO answer

void getBin(int num, char *str)
{
  *(str+5) = '\0';
  int mask = 0x10 << 1;
  while(mask >>= 1)
    *str++ = !!(mask & num) + '0';
}
like image 164
Florin Stingaciu Avatar answered Sep 24 '22 20:09

Florin Stingaciu