Home C++ Interview Programs Binary to Decimal C++ Binary to Decimal Program Definition
What Is Binary to Decimal Conversion? Binary (base 2) uses only digits 0 and 1. Decimal (base 10) is the everyday number system. Conversion turns a bit string into its base-10 value using powers of 2.
binary → decimal: sum of bit × 2^position
(rightmost bit has position 0)
Example: 101010
1×2⁵ + 0×2⁴ + 1×2³ + 0×2² + 1×2¹ + 0×2⁰
= 32 + 0 + 8 + 0 + 2 + 0
= 42 Binary Place values Decimal 10101032+8+2 42 10108+2 10 001014+1 5 11118+4+2+1 15
Approach
How to Convert Binary to Decimal in C++ Validate bits, then accumulate place values — or use the library parser.
Reject empty strings and any character that is not 0 or 1. Walk bits (right-to-left with powers, or left-to-right doubling). Add each bit’s contribution to a running total. Return the decimal result. Method Idea Time Best for Place value Right-to-left powers of 2 O(k)Interviews, clarity std::stoi base 2 Library parse O(k)Idiomatic C++ Doubling total = total*2 + bitO(k)Left-to-right walks
Pseudocode function BinaryToDecimal(bits):
validate bits contain only 0 and 1
total = 0
power = 1
for i from last index down to 0:
if bits[i] == '1':
total = total + power
power = power * 2
return total Reference
Cheat Sheet Keep these facts handy while writing the program.
Topic Detail Digits Only 0 and 1 Rightmost bit Weight 2⁰ = 1 Classic 101010 → 42Library std::stoi(s, nullptr, 2)Leading zeros Ignored in value (00101 = 5)
Try it
Live Preview Enter a binary string to see place values and the decimal result.
Trace
Worked Walkthrough — 101010 Start from the right with weight 1, then double the weight each step left.
bits: 1 0 1 0 1 0
pos: 5 4 3 2 1 0
0 × 2⁰ = 0
1 × 2¹ = 2
0 × 2² = 0
1 × 2³ = 8
0 × 2⁴ = 0
1 × 2⁵ = 32
Sum = 32 + 8 + 2 = 42 Code
C++ Programs Start with manual powers of 2. Then use std::stoi, and finish with the left-to-right doubling method.
1. Manual powers 2. std::stoi base 2 3. Doubling Example 1 — Manual Conversion Using Powers of 2 Validate bits, walk right-to-left, and add a power of 2 for every 1.
#include <iostream>
#include <string>
#include <stdexcept>
long long binaryToDecimalManual(std::string bits) {
while (!bits.empty() && bits.front() == ' ') {
bits.erase(bits.begin());
}
while (!bits.empty() && bits.back() == ' ') {
bits.pop_back();
}
if (bits.empty()) {
throw std::invalid_argument("Binary string must contain only 0 and 1");
}
long long total = 0;
long long powerOfTwo = 1;
for (int i = (int) bits.size() - 1; i >= 0; i--) {
char ch = bits[i];
if (ch != '0' && ch != '1') {
throw std::invalid_argument("Binary string must contain only 0 and 1");
}
if (ch == '1') {
total += powerOfTwo;
}
powerOfTwo *= 2;
}
return total;
}
int main() {
std::string binaryNumber = "101010";
long long decimalNumber = binaryToDecimalManual(binaryNumber);
std::cout << "Binary: " << binaryNumber << "\n";
std::cout << "Decimal: " << decimalNumber << "\n";
return 0;
} Binary: 101010
Decimal: 42 How It Works Trim spaces and reject an empty string. Start at the rightmost bit with weight 1. Add the current weight when the bit is 1. Double the weight after each bit (powerOfTwo *= 2). Reject any character that is not 0 or 1. Example 2 — Using std::stoi(..., nullptr, 2) Validate first, then let C++ parse the base-2 string.
#include <iostream>
#include <string>
#include <stdexcept>
int binaryToDecimalBuiltin(std::string bits) {
while (!bits.empty() && bits.front() == ' ') {
bits.erase(bits.begin());
}
while (!bits.empty() && bits.back() == ' ') {
bits.pop_back();
}
if (bits.empty()) {
throw std::invalid_argument("Binary string must contain only 0 and 1");
}
for (size_t i = 0; i < bits.size(); i++) {
char ch = bits[i];
if (ch != '0' && ch != '1') {
throw std::invalid_argument("Binary string must contain only 0 and 1");
}
}
return std::stoi(bits, nullptr, 2);
}
int main() {
std::string binaryNumber = "101010";
std::cout << "Binary: " << binaryNumber << "\n";
std::cout << "Decimal: " << binaryToDecimalBuiltin(binaryNumber) << "\n";
return 0;
} Binary: 101010
Decimal: 42 How It Works Trim and validate so only 0/1 remain. std::stoi(bits, nullptr, 2) parses the string as base 2.Returns a decimal int (use std::stoll for longer strings). Your own validation gives clearer errors than a bare throw. Great for production after you understand place values. Example 3 — Doubling Method For each bit from the left: total = total * 2 + bit.
#include <iostream>
#include <string>
#include <stdexcept>
long long binaryToDecimalDoubling(std::string bits) {
while (!bits.empty() && bits.front() == ' ') {
bits.erase(bits.begin());
}
while (!bits.empty() && bits.back() == ' ') {
bits.pop_back();
}
if (bits.empty()) {
throw std::invalid_argument("Binary string must contain only 0 and 1");
}
long long total = 0;
for (size_t i = 0; i < bits.size(); i++) {
char ch = bits[i];
if (ch != '0' && ch != '1') {
throw std::invalid_argument("Binary string must contain only 0 and 1");
}
total = total * 2 + (ch == '1' ? 1 : 0);
}
return total;
}
int main() {
std::cout << binaryToDecimalDoubling("1010") << "\n";
std::cout << binaryToDecimalDoubling("00101") << "\n";
return 0;
} How It Works Start total at 0 and walk left to right. Each step: multiply by 2 (shift left), then add the next bit. No reverse index needed — Horner form of the place-value sum. 1010 becomes 10; 00101 becomes 5.Leading zeros do not change the final value. Edge Cases & Pitfalls Check these before calling the solution done.
Invalid Only 0 and 1 Any other digit is invalid. Reject early instead of converting silently.
Empty Empty string Treat as invalid. Throw or return a documented error — do not invent a value.
Overflow Long bit strings int/long long have limits. Use stoll or reject inputs that are too long.
std::pow Prefer integer doubling Floating pow can round. Multiply the weight by 2 each step instead.
Analysis
Time and Space Complexity Program Time Extra space Manual / doubling / stoi O(k)O(1) beyond the string
Here k is the number of bits. Every method visits each bit a constant number of times.
Remember
Key Takeaways Idea: each bit contributes bit × 2^position.
Classic: 101010 → 42.
Validate: only 0 and 1 before converting.
Shortcut: std::stoi(s, nullptr, 2) after you know the math.
One line: add each bit times its power of two — that is the decimal value.
Frequently Asked Questions How do I convert binary to decimal in C++? Use place-value powers of 2, the doubling method, or std::stoi(bits, nullptr, 2). All return the same decimal value when the input is valid.
Why validate binary input first? Binary may only contain 0 and 1. Validation prevents wrong answers and std::invalid_argument from std::stoi.
What does std::stoi(s, nullptr, 2) do? It parses string s as base 2 and returns a decimal int. Use std::stoll for longer bit strings.
What is the time complexity? O(k), where k is the number of bits.
Do leading zeros matter? No. 00101 is still 5 in decimal.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
18 people found this page helpful
Helpful Share Copy link Suggestion