C Program to Convert a Binary Number to a Decimal Number

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

Expected Output:

1st run:

2nd run:

How it works

Here are the steps to convert a binary number to a decimal number:

Example 1: Convert binary number 100 to its decimal equivalent.

Example 2: Convert binary number 1001 to its decimal equivalent.

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

Iteration remainder decimal bin
After 1st iteration remainder = 10101 % 10 = 1 decimal = 0 + 1 * (2^0) = 1 bin = 10101 / 10 = 1010
After 2nd iteration remainder = 1010 % 10 = 0 decimal = 1 + 0 * (2^1) = 1 bin = 1010 / 10 = 101
After 3rd iteration remainder = 101 % 10 = 1 decimal = 1 + 1 * (2^2) = 5 bin = 101 / 10 = 10
After 4th iteration remainder = 10 % 10 = 0 decimal = 5 + 0 * 2^3 = 5 bin = 10 / 10 = 1
After 5th iteration remainder = 1 % 10 = 1 decimal = 5 + 1 * (2^4) = 21 bin = 1 / 10 = 0

 

Leave a Comment

%d bloggers like this: