c++ convert binary string to decimal
To convert a binary string to a decimal number in C++, you can use the following steps:
Include the necessary header file: In order to use the required functions and objects for string manipulation and conversion, you need to include the
<string>
and<cmath>
header files.Get the binary string: Obtain the binary string that you want to convert to a decimal number. This can be done by either reading user input or extracting the string from a file or another source.
Reverse the binary string: Since the least significant bit (LSB) is at the rightmost position in a binary number, you need to reverse the binary string to perform the conversion correctly. This can be achieved using the
reverse()
function from the<algorithm>
header.Convert each digit to decimal: Iterate over each character in the reversed binary string and convert it to its decimal value. The decimal value of each digit can be calculated by multiplying it by 2 raised to the power of its position. For example, the first digit (rightmost digit) is multiplied by 2^0, the second digit is multiplied by 2^1, and so on.
Sum the decimal values: Add up all the decimal values obtained in the previous step to calculate the decimal equivalent of the binary string.
Print or use the decimal result: You can now print the decimal result or use it further in your program as needed.
Here is an example code snippet that demonstrates the conversion process:
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
int main() {
std::string binaryString;
std::cout << "Enter a binary number: ";
std::cin >> binaryString;
std::reverse(binaryString.begin(), binaryString.end());
int decimalNumber = 0;
for (size_t i = 0; i < binaryString.length(); ++i) {
if (binaryString[i] == '1') {
decimalNumber += std::pow(2, i);
}
}
std::cout << "Decimal equivalent: " << decimalNumber << std::endl;
return 0;
}
In this example, the user is prompted to enter a binary number, which is then reversed using std::reverse()
. The reversed binary string is then iterated over, and each digit is converted to its decimal value using the std::pow()
function. The decimal values are added together, and the final result is printed as the decimal equivalent of the binary string.