Example:
Input any number: 22
Output binary number: 00000000000000000000000000010110 (in 4 byte integer representation)
Required knowledge:
Basic C programming, Bitwise operator, Loop, ArrayProgram:
/**
* C program to convert decimal to binary number system using bitwise operator
*/
#include <stdio.h>
#define INT_SIZE sizeof(int) * 8 //Size of int in bits
int main()
{
int num, index, i;
int bin[INT_SIZE];
printf("Enter any number: ");
scanf("%d", &num);
index = INT_SIZE;
//Converts decimal to binary
while(index!=0)
{
index--;
//Store 1 if LSB is set otherwise 0
bin[index] = num & 1;
//Shift bits of num to one position right
num >>= 1;
}
//Prints the converted binary
printf("Converted binary (in %d byte integer representation): ", sizeof(int));
for(i=0; i<INT_SIZE; i++)
{
printf("%d", bin[i]);
}
return 0;
}
Output
Enter any number: 22
Converted binary (in 4 byte integer representation): 00000000000000000000000000010110
Converted binary (in 4 byte integer representation): 00000000000000000000000000010110
Happy coding ;)
You may also like
- Bitwise operator programming exercises index.
- C program to convert decimal to binary number system without using bitwise operator.
- C program to find one's complement of a binary number.
- C program to find two's complement of a binary number.
- C program to get nth bit of a number.
- C program to set nth bit of a number.
- C program to clear nth bit of a number.
- C program to toggle nth bit of a number.
- C program to count trailing zeros in a binary number.
- C program to count leading zeros in a binary number.
- C program to flip bits of a binary number using bitwise operator.
- C program to total number of zeros and ones in a binary number.
- C program to swap two numbers using bitwise operator.