C++ Program to Convert Binary to Decimal Number
2 raised to the power of its position, then summing these values. For example, use a loop to process each character of the binary string and calculate the decimal value.Examples
How to Think About It
Algorithm
Code
#include <iostream> #include <string> #include <cmath> int main() { std::string binary; std::cout << "Enter a binary number: "; std::cin >> binary; int decimal = 0; int length = binary.length(); for (int i = 0; i < length; ++i) { if (binary[i] == '1') { decimal += static_cast<int>(std::pow(2, length - i - 1)); } } std::cout << "Decimal equivalent: " << decimal << std::endl; return 0; }
Dry Run
Let's trace the binary number '101' through the code.
Input
binary = '101', length = 3, decimal = 0
First iteration (i=0)
binary[0] = '1', decimal += 2^(3-0-1) = 2^2 = 4, decimal = 4
Second iteration (i=1)
binary[1] = '0', no addition, decimal = 4
Third iteration (i=2)
binary[2] = '1', decimal += 2^(3-2-1) = 2^0 = 1, decimal = 5
End
decimal = 5, output printed
| Iteration | Character | Power | Value Added | Decimal Total |
|---|---|---|---|---|
| 0 | 1 | 2 | 4 | 4 |
| 1 | 0 | 1 | 0 | 4 |
| 2 | 1 | 0 | 1 | 5 |
Why This Works
Step 1: Reading Input
The program reads the binary number as a string to process each digit individually.
Step 2: Calculating Decimal Value
Each '1' digit contributes 2 raised to the power of its position index from right to left, summed to get the decimal number.
Step 3: Using pow Function
The std::pow function calculates powers of 2 for each digit's position.
Alternative Approaches
#include <iostream> #include <string> int main() { std::string binary; std::cout << "Enter a binary number: "; std::cin >> binary; int decimal = 0; for (char bit : binary) { decimal = (decimal << 1) + (bit - '0'); } std::cout << "Decimal equivalent: " << decimal << std::endl; return 0; }
#include <iostream> #include <string> int main() { std::string binary; std::cout << "Enter a binary number: "; std::cin >> binary; int decimal = std::stoi(binary, nullptr, 2); std::cout << "Decimal equivalent: " << decimal << std::endl; return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through each binary digit once, so time grows linearly with input size.
Space Complexity
Only a few variables are used regardless of input size, so space is constant.
Which Approach is Fastest?
Bit shifting is faster than using pow because it uses simple binary operations instead of floating-point math.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using pow in loop | O(n) | O(1) | Simple understanding, educational |
| Bit shifting | O(n) | O(1) | Efficient and fast for large inputs |
| stoi with base 2 | O(n) | O(1) | Concise code, requires C++11+ |