Pages

Wednesday, October 21, 2015

Printing binary numbers In C

Because I am following K&R page by page, example by example I decided to document my effort here.  Sometimes I will be posting the answer to the question and sometimes like today I will be posting some code that solves a problem.

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:
  1. 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.
  2. 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.
  3. leadingzero is just a nice addition, in my opinion to avoid printing leading zeroes.

And that is for this exercise.