OverIQ.com

C Program to convert a decimal number to a binary number

Last updated on September 24, 2020


The following is a C program to convert a decimal number to a binary number:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*******************************************************
 Program to convert a decimal number to a binary number
 ******************************************************/

#include<stdio.h> // include stdio.h library
#include<math.h> // include math.h library

int main(void)
{   
    long long num, bin = 0;    
    int i = 0, rem;

    printf("Enter a decimal number: ");
    scanf("%lld", &num);      

    while(num != 0)
    {
        rem = num % 2;  // get the remainder 
        bin = rem * (long long)pow(10, i++) + bin;  
        num /= 2;  // get the quotient
    }       

    printf("%lld", bin);        

    return 0; // return 0 to operating system
}

Try it now

Expected Output: 1sr run:

1
2
Enter a decimal number: 4
100

2nd run:

1
2
Enter a decimal number: 123456
11110001001000000

How it works: #

To convert a decimal number to a binary number, we follow these steps:

Step 1: Divide the decimal number continuously by 2 and right the remainder on the right-hand side of the dividend. We repeat this process until we get the quotient 0.

Step 2: Write the remainders from bottom to top.

Let's take some examples now.

Example 1: Convert decimal number 5 to a binary.

Step 1:

Quotient Remainder
5/2 2 1
2/2 1 0
1/2 0 1

Step 2:

\(5_{10}\) = \(101_2\)

Example 2: Convert decimal number 123 to a binary.

Step 1:

Quotient Remainder
123/2 61 1
61/2 30 1
30/2 15 0
15/2 7 1
7/2 3 1
3/2 1 1
1/2 0 1

Step 2: \(123_{10}\) = \(1111011_2\)

The following table shows what happens at each iteration of the loop (assuming num = 4):

Iteration rem bin num i
After 1st iteration rem = 4 % 2 = 0 bin = 0 * (10^0) + 0 = 0 num = 4 / 2 = 2 i = 2
After 2nd iteration rem = 2 % 2 = 0 bin = 0 * (10^1) + 0 = 0 num = 2 / 2 = 1 i = 3
After 3rd iteration rem = 1 % 2 = 1 bin = 1 * (10^2) + 0 = 100 num = 1 / 2 = 0 i = 4