I'm writing a program to convert an integer to 32-bit binary. The problem is with the output - it comes backwards.
#include <stdio.h>
int main() {
long number, binary, num2;
printf("Enter an integer: ");
scanf("%ld", &number);
for (num2 = (number * 2) / 2; num2 > 0; num2 /= 2) {
binary = num2 % 2;
printf("%ld", binary);
}
putchar('\n');
return 0;
}
So if I put '6' it shows as 011 and it has to be 110
Also, how do I output the rest of '0's? So that the whole output in this case would be:
00000000 00000000 00000000 00000110
Here is a simple portable implementation for 32-bit numbers:
If you want to print the binary number, you should print the bits backwards. Watch this:
You are printing it the forward order which will give you 011. So you should keep the binary bits by putting them in a variable and finally print them back.
Try This
You compute digits starting from the right, which is why your output shows the right-most digit first. Here is a way that starts from the left, using a bitmask, and does not convert your value to unsigned which may change the bits:
It's so much easier to use a recursive function for this:
Output:
PS If you used
uint32_t
fornum
instead oflong
, you will get the 32 bits of output.Simply examine the bits in the order in which you want them output. I have used a
unsigned long
cast for the shifting, because the result of shifting bits of a signed value into the sign bit is undefined.Program output: