C++ program to convert binary number to decimal and decimal to binary


In this example, you will learn about C++ program to convert binary number to decimal and decimal to binary number.

C++ program to convert binary number to decimal and decimal to binary

Binary to Decimal program in C++

Let’s take a look at the program logic:

  1. First, extract digits from the right side of the number.
  2. The extracted digit is then multiplied by the proper base (power of 2).
  3. Finally, these digits are added together to get an equivalent decimal number.

 

C++ program to convert binary to decimal

Example: C++ example to convert binary number to decimal number

//C++ program to convert binary to decimal
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
   long long num;
   int decimalNum, i, rem;

   cout << "Enter any binary number: ";
   cin >> num;

   decimalNum = 0;
   i = 0;

   //converting binary to decimal
   while (num != 0)
   {
      rem = num % 10;
      num /= 10;
      decimalNum += rem * pow(2, i);
      ++i;
   }

   cout << "Equivalent Decimal number: " << decimalNum << endl;

   return 0;
}

Output

C++ program to convert binary to decimal

Decimal to Binary number program in C++

Here, we are going to convert decimal number to binary number.

Let’s take a look at program logic:

  1. The remainder is stored in a variable when it is divided by 2
  2. Divide the number by 2
  3. Repeat these steps till the number is greater than zero

C++ program to convert decimal to binary

Example: C++ program to convert the decimal number to the binary

//C++ program to convert decimal to binary

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
   int num, binaryNum = 0;
   int i = 1, rem;

   cout << "Enter any decimal number: ";
   cin >> num;

   //while loop to convert decimal to binary
   while (num != 0)
   {
      rem = num % 2;
      num /= 2;
      binaryNum += rem * i;
      i *= 10;
   }

   cout << "Equivalent Binary Number: " << binaryNum << endl;

   return 0;
}

Output

C++ program to convert decimal to binary