In this example, you will learn about C++ program to convert binary number to decimal and decimal to binary number.
Let’s take a look at the program logic:
//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
Here, we are going to convert decimal number to binary number.
Let’s take a look at program logic:
//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