Converting between binary and decimal is a common task in computer programming.
Binary numbers are numbers that use only two digits, 0 and 1, while decimal numbers use ten digits, 0 to 9.
In this tutorial, we will write a C++ program to convert binary numbers to decimal and vice-versa.
Converting Binary to Decimal
To convert a binary number to decimal, we use the following algorithm:
- Initialize a variable ‘decimal’ to zero.
- Read the binary number as a string.
- Starting from the rightmost digit of the string, multiply the digit by 2^i, where i is the position of the digit, starting from zero.
- Add the result of step 3 to the ‘decimal’ variable.
- Repeat steps 3 and 4 for all the digits in the binary string.
- The value of ‘decimal’ is the decimal equivalent of the binary number.
Here is the C++ code for the algorithm:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int binaryToDecimal(string binary) {
int decimal = 0;
int power = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
int digit = binary[i] - '0';
decimal += digit * pow(2, power);
power++;
}
return decimal;
}
int main() {
string binary;
cout << "Enter a binary number: ";
cin >> binary;
cout << binary << " in decimal is " << binaryToDecimal(binary) << endl;
return 0;
}
Converting Decimal to Binary
To convert a decimal number to binary, we use the following algorithm:
- Initialize a variable ‘binary’ to an empty string.
- Read the decimal number.
- Divide the decimal number by 2 and record the remainder.
- Repeat step 3 until the decimal number is zero.
- The binary equivalent is the remainders from step 3, read in reverse order.
Here is the C++ code for the algorithm:
#include <iostream>
#include <string>
using namespace std;
string decimalToBinary(int decimal) {
string binary = "";
while (decimal > 0) {
int remainder = decimal % 2;
binary = to_string(remainder) + binary;
decimal /= 2;
}
return binary;
}
int main() {
int decimal;
cout << "Enter a decimal number: ";
cin >> decimal;
cout << decimal << " in binary is " << decimalToBinary(decimal) << endl;
return 0;
}
In conclusion, converting binary to decimal and vice-versa is a straightforward process in C++.
We use the algorithms described above to perform the conversion.
By following these algorithms, we can easily write a program to convert binary and decimal numbers in C++.




