Decimal to binary algorithm in C
algorithm, binary, c, decimal
Solution
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';
}
Problem
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); ```