To convert a decimal number into a binary number using bit masking, perform the following steps:
- Enter a decimal value. The decimal number entered is internally stored in the form of binary digits.
- Assign a number 1 followed by 31 zeros to a variable called mask.
- Mask each of the binary digits of the decimal number one by one, beginning from the most significant bit. Apply an AND operation between the binary digits of the entered decimal number and the binary digits in the mask variable.
- Right-shift the binary digits in the mask variable by 1 bit making it 0 1 followed by 30 zeros.
- Repeat this procedure. Apply the AND operation between the entered decimal number and the mask variable and the resultant binary digit is displayed on the screen. The procedure is repeated until the value in the mask variable becomes 0.
The program for converting a decimal number into binary using bit masking is as follows:
decintobin.c
#include <stdio.h>
void main()
{
int i, totbits;
unsigned mask,num;
printf("Enter decimal value: ");
scanf("%d", &num);
totbits=32;
mask = 1 << (totbits - 1);
for(i = 0; i < totbits; i++)
{
if((num & mask) == 0 )
printf("0");
else
printf("1");
mask >>= 1;
}
}
Now, let's go behind the scenes.