C++ Program to Convert Binary to Decimal

In this tutorial, we will write a program to convert a binary number into decimal in C++. Before that, you must have knowledge of the following topics in C++.

Binary number

The binary numbers are based on 0 and 1, so it is a base 2 number. They are the combination of 0 and 1. For example, 1001, 110101, etc.

Decimal Number

These are the numbers with a base of 10, which ranges from 0 to 9. These numbers are formed by the combination of 0 to 9 digits such as 24, 345, etc.

Here is the chart where for the equivalent value of decimal and binary numbers.

Decimal to binary

Now let us go through a program for the conversion of binary to decimal in C++.


C++ Program to Convert Binary to Decimal

The program asks the user to enter a binary number and using a while loop it calculates the decimal value. Lastly, display the equivalent decimal value.

#include <iostream>
using namespace std;

int main()
{
   int bin, deci = 0, i = 1, rem;

   cout << "Enter a Binary Number: ";
   cin >> bin;

   while (bin != 0)
   {
      rem = bin % 10;
      deci = deci + (rem *i);
      i = i * 2;
      bin = bin / 10;
   }

   //Display the equivalent decimal number
   cout << "Decimal Value: " << deci;

   return 0;
}

Output:

Enter a Binary Number: 1010
Decimal Value: 10

Also, check out a similar program: