This is my code for printing numbers in binary format in C:
#include <stdio.h>
int main() {
unsigned long long int x,mask,temp;
int leadingzero=1;int i;
mask=1;
printf("Enter a decimal number: ");
if (scanf("%llu",&x)) {
printf("Binary representation: ");
i=sizeof(x)*8;
mask = mask << i-1;
while (i) {
if ((mask & x ) == mask) {
printf("1");
leadingzero=0;}
else {
if (!leadingzero) { printf("0"); }
}
x=x<<1; i--;
}
printf("\n");
}//if scanf was ok
}
The concept is the following:
- Create a mask that has a 1 in the MSBit of a variable of the same size of the decimal to convert. Both, the mask and the input variable,x, are unsigned int. In my machine, a x86_64, that means 4 bytes of length. So, in my case mask has a 1 in the bit number 31 and 0 in the rest of the bits.
- Start a while loop of 32 iterations. In every iteration execute a bitwise AND (&) between the mask and x, this one shifthed to the right one digit per iteration. When the the MSB of the shifted version of x is one, the AND result in the same value of mask, so a 1 is printed.
- leadingzero is just a nice addition, in my opinion to avoid printing leading zeroes.
And that is for this exercise.