C Program to convert decimal to binary number
Objective
Write a C program to convert a decimal number to binary using Bitwise Operators.
Algorithm / Approach
- Read an integer
n. - Start a
forloop counting down from 15 to 0 (for a 16-bit binary representation). - Inside the loop, use the Right Shift operator:
k = n >> c. - Use the Bitwise AND operator
if (k & 1)to check if the right-most bit is a 1 or a 0. - Print "1" or "0" accordingly.
main.c
#include<stdio.h>
int main( ) {
int n, c, k;
printf("Enter a number ");
scanf("%d",&n);
printf("Binary number of %d =\n",n );
for(c = 15;c >=0; c--) {
k = n >> c;
if(k & 1)
printf("1");
else
printf("0");
}
printf("\n");
return 0;
}
Expected Output
Enter a number 12 Binary number of 12 = 0000000000001100
Explanation of the Program
- Computers store integers in binary natively. This program extracts that binary representation directly from memory rather than performing mathematical division.
- The Right Shift operator (
>>) slides all the bits of the number to the right bycpositions. - The Bitwise AND operator (
& 1) acts as a mask. It looks exclusively at the very last bit on the right. If that bit is a 1, the result is 1 (True). If it is a 0, the result is 0 (False).
Complexity
Time Complexity
O(1) - Loop runs a fixed 16 times.
Space Complexity
O(1)