Program to convert a binary number to a decimal number in C/C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code
  4. Download Code

Code


To copy code: Click  View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


Prerequisite: Learn the basics of converting binary to decimal

1. First we enter a binary number (suppose 10111). Now the control reaches the while loop where it checks the condition (b>0) which is TRUE as (10111>0) so the body of the loop is executed. Here, rem = b%10 means that we are dividing the variable ‘b’ with 10 and storing the remainder in the variable ‘rem’. Please note that ‘%’ or modulus division of two numbers returns the remainder. So, 12%10 will return 2 and so on.

On first pass: rem=(10111%0)=1,n=0+1*pow(2,0)=1,b=1011

On second pass: rem=(1011%10)=1,n=1+1*pow(2,1)=1+2, b=101

On third pass: rem=(101%10)=1,n=3+1*pow(2,2)=3+4,b=10

On fourth pass: rem=(10%10)=0,n=7+0*pow(2,3)=7+0,b=1

On fifth pass: rem=(1%10)=0,n=7+1*pow(2,4)=7+16,b=0

Thus finally, we get the required result 23.

Output:

Enter binary number: 10111(Press Enter)
Decimal Equivalent =23