C++ Binary to Decimal Program

Beginner
5 min read
Updated: Oct 2026
3 programs
Live preview

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.

Remember
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
BinaryPlace valuesDecimal
10101032+8+242
10108+210
001014+15
11118+4+2+115

How to Convert Binary to Decimal in C++

Validate bits, then accumulate place values — or use the library parser.

  1. Reject empty strings and any character that is not 0 or 1.
  2. Walk bits (right-to-left with powers, or left-to-right doubling).
  3. Add each bit’s contribution to a running total.
  4. Return the decimal result.
MethodIdeaTimeBest for
Place valueRight-to-left powers of 2O(k)Interviews, clarity
std::stoi base 2Library parseO(k)Idiomatic C++
Doublingtotal = total*2 + bitO(k)Left-to-right walks

Pseudocode

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

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
DigitsOnly 0 and 1
Rightmost bitWeight 2⁰ = 1
Classic101010 → 42
Librarystd::stoi(s, nullptr, 2)
Leading zerosIgnored in value (00101 = 5)

Live Preview

Enter a binary string to see place values and the decimal result.

Digits 0 and 1 only. Tap a chip or type a bit string.

Result
binary = 101010
32 + 8 + 2 = 42
Decimal = 42

Worked Walkthrough — 101010

Start from the right with weight 1, then double the weight each step left.

Calculation
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

C++ Programs

Start with manual powers of 2. Then use std::stoi, and finish with the left-to-right doubling method.

Example 1 — Manual Conversion Using Powers of 2

Validate bits, walk right-to-left, and add a power of 2 for every 1.

C++
#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;
}

How It Works

  1. Trim spaces and reject an empty string.
  2. Start at the rightmost bit with weight 1.
  3. Add the current weight when the bit is 1.
  4. Double the weight after each bit (powerOfTwo *= 2).
  5. 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.

C++
#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;
}

How It Works

  1. Trim and validate so only 0/1 remain.
  2. std::stoi(bits, nullptr, 2) parses the string as base 2.
  3. Returns a decimal int (use std::stoll for longer strings).
  4. Your own validation gives clearer errors than a bare throw.
  5. Great for production after you understand place values.

Example 3 — Doubling Method

For each bit from the left: total = total * 2 + bit.

C++
#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

  1. Start total at 0 and walk left to right.
  2. Each step: multiply by 2 (shift left), then add the next bit.
  3. No reverse index needed — Horner form of the place-value sum.
  4. 1010 becomes 10; 00101 becomes 5.
  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.

Time and Space Complexity

ProgramTimeExtra space
Manual / doubling / stoiO(k)O(1) beyond the string

Here k is the number of bits. Every method visits each bit a constant number of times.

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

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.
Binary may only contain 0 and 1. Validation prevents wrong answers and std::invalid_argument from std::stoi.
It parses string s as base 2 and returns a decimal int. Use std::stoll for longer bit strings.
O(k), where k is the number of bits.
No. 00101 is still 5 in decimal.

Next: Common Divisors

List every positive integer that divides both numbers.

Common divisors tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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