# How to Convert Binary Number into Decimal in C++

In today’s post, I will teach you to write a C++ program that converts a binary number into decimal. It will take a binary number as input and gives a decimal number as output.

## Binary and Decimal Numbers:

Decimal is a base-10 number system. It uses 10 digits from 0 to 9 to represent a number. Because there are 10 decimal numbers, the value of each digit increases by a factor of 10.

Binary is a base-2 number system. It uses only 0 and 1 to represent a number. Because there are only two binary numbers, the value of each digit increases by a factor of 2.

## Program Logic:

Let’s see how we convert a binary number into decimal in real-world. For example, if we have a binary number 1010 then decimal equivalent is calculated as:

#### 1010=(1*8)+(0*4)+(1*2)+(0*1)=8+0+2+0=10

What we does above is multiplied each binary digit by its digit value which is determined by its position i.e. factor of 2. then we sum up all the value to compute total which is a decimal number.

Recommended Reading: How to Convert Decimal Number into Binary in C++

In coding, we declared four variables. Two for storing binary and decimal numbers, and two for calculating them.

A loop runs until binary number reaches 0 which means number is completely converted. Whenever this loop runs, binary number is divided by 10 and remainder is stored in a variable.

A variable named base is multiplied by two so it will provide factor of two for conversion. Remainder can be either 0 or 1 which decides whether this digit possesses value or not.

After that, remainder and factor of two gets multiplied which is shown in above simple conversion. Decimal number is added all the times to get a single number.

## Dry Run:

Lets see how this code is executed by computer. Suppose the number entered by user is 1010. Then Loop starts in the following manner:

When binary=1010

rem=1010%10=0
decimal=0+(0*1)=0
base=1*2=2
binary=1010/10=101

When binary=101

rem=101%10=1
decimal=0+(1*2)=2
base=2*2=4
binary=101/10=10

When binary=10

rem=10%10=0
decimal=2+(0*4)=2
base=4*2=8
binary=10/10=1

When binary=1

rem=1%10=1
decimal=2+(1*8)=10
base=8*2=16
binary=1/10=0

## Program Output:

I hope now you can convert binary number into decimal in C++.

If you liked this article, then please consider sharing it with your friends and leaving a comment below.