To convert a binary number into a decimal, perform the following steps:
- Enter a binary number.
- Apply a mod 10 (% 10) operator to the binary digits of the binary number to isolate the last bit of the binary number.
- Left-shift the binary digit isolated in step 2 to multiply it by the power of 2.
- Add the product of the previous multiplication to the variable that will store the result, that is, the decimal number. Let's call the variable dec.
- The last digit of the binary number is truncated.
- Repeat step 2 to step 4 until all the bits of the binary digits are over.
- Display the decimal in the dec variable.
The program for converting a binary number into a decimal is as follows:
binintodec.c
#include <stdio.h>
void main()
{
int num,bin,temp,dec=0,topower=0;
printf("Enter the binary number: ");
scanf("%d",&bin);
temp=bin;
while(bin >0)
{
num=bin %10;
num=num<<topower;
dec=dec+num;
topower++;
bin=bin/10;
}
printf("The decimal of %d is %d\n",temp,dec);
}
Now, let's go behind the scenes to understand the code better.