C Program to Convert a Binary Number to a Decimal Number
Last updated on September 24, 2020
The following is a C program to convert a binary number to a decimal 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 | /*******************************************************
* Program to convert a binary number to decimal number
********************************************************/
#include<stdio.h> // include stdio.h
#include<math.h> // include stdio.h
int main()
{
long int bin, remainder, decimal = 0, i = 0;
printf("Enter a binary number: ");
scanf("%d", &bin);
while(bin != 0)
{
remainder = bin % 10;
decimal += remainder * (int)pow(2, i++);
bin = bin / 10;
}
printf("Decimal: %d", decimal);
return 0;
}
|
Expected Output: 1st run:
1 2 | Enter a binary number: 100
Decimal: 4
|
2nd run:
1 2 | Enter a binary number: 1000011
Decimal: 67
|
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.
1 2 3 | => ( 1 * 2^2 ) + ( 0 * 2^1 ) + ( 0 * 2^0 )
=> 4 + 0 + 0
=> 4
|
Example 2: Convert binary number 1001
to its decimal equivalent.
1 2 3 | => ( 1 * 2^3 ) + ( 0 * 2^2 ) + ( 0 * 2^1 ) + ( 1 * 2^0 )
=> 8 + 0 + 0 + 1
=> 9
|
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 |
Load Comments