How to do it…

To convert a decimal number into a binary number by making use of a bitwise operator, perform the following steps:

  1. Enter a decimal number. This number is internally stored in the form of binary digits.
  2. Isolate the least significant bit of the decimal number by applying a logical AND operation between the entered decimal number and value 1.
  3. The least significant bit that results from step 2 is stored in an array.
  4. Right-shift the binary digits of the decimal number by 1 bit. On shifting to the right, the second least significant bit will become the least significant bit.
  5. Repeat steps 2 to 4 until all the binary digits of the decimal number are placed into the array.
  6. The binary digits assigned to the array are the binary version of the entered decimal number. Display the binary digits in an array to get the result.

The program for converting a decimal into a binary number using a bitwise operator is as follows:

convertintobin.c
#include <stdio.h>
void main()
{
int num,i,x,temp;
int p[10];
printf("Enter Decimal Number : ");
scanf("%d",&num);
temp=num;
x=0;
while(num > 0)
{
if((num & 1) == 0 )
{
p[x]=0; x++;
}
else
{
p[x]=1;
x++;
}
num = num >> 1;
}
printf("Binary of %d is ",temp);
for(i=x-1;i>=0;i--)printf("%d",p[i]);
}

Now, let's go behind the scenes.