C Program to Convert Decimal to Binary using Bitwise AND operator

C Program to Convert Decimal to Binary using Bitwise and operator

Output :
Above program is just to know the size of integer variable in C Programming (Borland C/C++ Compiler.) Integer number can be represented by 16 bits.
To convert the Decimal Number into Binary , Check First MSB bit of number , if it is 1 then display ‘1’ otherwise display ‘0’.
Program :
Output :

Explanation of Decimal to Binary Program :

In this program we have accepted the decimal number using following lines –

Inside the function we have initialized mask variable with 32768.

i.e Binary representation of the number is 1000 0000 0000 0000

Now inside iteration we need to follow same steps : If result of mask is Zero then Print 0 else Print 1.

Consider the first iteration Masking will be like this –

Now right shift mask by 1 so that new mask variable will contain following value –

As mask variable is not equal to 0 so once again while loop will be executed and in the next iteration of while loop following numbers will be ANDed.

Similarly, In each iteration we are shifting mask variable by 1 to right and ANDing the mask with number.

Algorithm for Decimal to Binary using Bitwise Operator :

  1. Initialize ‘mask’ variable with 32768 [1000 0000 0000 0000]
  2. Perform ANDing of two number’s (i.e Given variable and  Mask variable )
  3. Check whether the Result of ANDing is 0 or not , if Yes Display 0 otherwise Display 1
  4. Right shift mask variable by 1 [0100 0000 0000 0000]
  5. Now check for Second bit , whether it is 0 or 1
  6. Goto step 3 until ‘mask’ becomes Zero  [ 0000 0000 0000 0000 ]

Why We are right shifting Mask Variable ?

We have kept given number as it is but in each iteration we have right shifted given number by 1 and masked it with original number. Main purpose of doing this is to check bit status of all the bits of given number.
Decimal to Binary Conversion using Bitwise Operators
In the 13th iteration mask variable will be –