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.
C++ Code to Convert Binary Number into Decimal:
using namespace std;
cout<<"*CONVERT BINARY NUMBER INTO DECIMAL*"<<endl;
cout<<"ENTER A BINARY NUMBER: ";
cout<<"\n DECIMAL OF GIVEN NUMBER IS: "<<decimal;
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:
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.
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.
Lets see how this code is executed by computer. Suppose the number entered by user is 1010. Then Loop starts in the following manner:
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.
You can also Click Here To Download Exercise Files.