We use numbers in our everyday life in decimal form. Decimal numbers have 10 symbols (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9). These ten symbols are used to represent any decimal number. The example of decimal numbers are 897513709, 8790 etc. Decimal numbers are sometimes represented as (897513709)10 or (8790)10.
On the other hand, binary numbers have only two symbols (0 and 1). So the base of binary number is 2. In computer or in any digital storage, all numbers (in fact all information) are stored in binary form. Binary equivalent of 897513709 is 110101011111101111100011101101, also written as (110101011111101111100011101101)2. Here we’ll see how to write C program to convert number from decimal to binary.
Recursive C Function to Convert Decimal to Binary
#include <stdio.h>
void binary(int n)
{
if(n > 0)
{
binary(n/2);
printf("%d", n%2);
}
}
void main()
{
int num = 0;
printf("Enter an integer: ");
scanf("%d", &num);
printf("Binary of %d: ", num);
binary(num);
printf("\n");
}
This program takes an integer as input and calls the binary() function to print that number in binary format.
Here is the output of the program.
Using Bitwise Operation
We can make use of bitwise operations to print binary number.
#include <stdio.h>
void main()
{
int num = 0, i, tmp;
printf("Enter an integer: ");
scanf("%d", &num);
printf("Binary of %d: ", num);
i = sizeof(num) * 8 - 1;
while(i >= 0) printf("%d", (num >> i--)&1?1:0);
printf("\n");
}