Place Values
1, 2, 4, 8…
Each bit position is a power of two, starting at 20 on the right.
Binary (base 2) uses only bits 0 and 1; decimal (base 10) is the everyday number system. This tutorial covers place values, a live preview, algorithm steps, worked C++ examples, edge cases, and complexity.
1, 2, 4, 8…
Each bit position is a power of two, starting at 20 on the right.
Sum 2^i
Walk bits right-to-left; add 2^power for every 1 bit.
Built-in
Parse a binary string as base 2 and get a decimal int in one call.
Only 0 / 1
Reject empty strings and any character outside {0, 1}.
Try any bits
Type a binary string and convert it to decimal instantly.
Complexity
One pass over k bits; extra space stays O(1) beyond the input.
Binary-to-decimal conversion turns a base-2 string into a base-10 integer. Each bit contributes a power of two: the rightmost bit is 20, then 21, 22, and so on.
You can sum those place values by hand, or call std::stoi(bits, nullptr, 2). Classic example: 101010 → 32 + 8 + 2 = 42.
It trains place-value thinking, string loops, validation, and the habit of explaining O(k) bit complexity in interviews.
Only 1-bits contribute; 0-bits add nothing.
Anything outside 0/1 is not a binary string.
Manual loop for interviews; std::stoi(s, nullptr, 2) for apps.
int/long long can overflow; prefer a big-integer library for huge bit strings.
In short: for each 1-bit at position i (from the right), add 2i — or just call std::stoi(bits, nullptr, 2).
Given a binary string of 0s and 1s, return its decimal integer value.
// Example: "101010"
// 1*32 + 0*16 + 1*8 + 0*4 + 1*2 + 0*1 = 42 | Item | Type | Description |
|---|---|---|
bits | str | Non-empty string containing only characters 0 and 1. |
| Return / print | int | Decimal integer value of that binary number. |
function binaryToDecimal(s):
if s has characters other than 0 and 1:
return error
total = 0
power = 0
for bit from right to left in s:
if bit == '1':
total = total + (2 ^ power)
power = power + 1
return total | Method | Idea | Notes |
|---|---|---|
| Place-value loop | Add 2^i for each 1-bit from the right | Best for showing interview math |
std::stoi(bits, nullptr, 2) | Built-in base-2 parse | Shortest production style |
| Goal | Pattern |
|---|---|
| Validate bits | all(ch in "01" for ch in bits) |
| Walk right-to-left | for (i = len-1; i >= 0; i--) |
| Add place value | total += powerOfTwo |
| Built-in convert | std::stoi(bits, nullptr, 2) |
| Doubling method | total = total * 2 + bit left-to-right |
| Classic check | "101010" → 42 |
Same decimal answer — different clarity and interview signaling.
sum 2^iShows powers of two clearly; preferred whiteboard style
built-inIdiomatic C++ for real applications
2*total + bitLeft-to-right Horner form; no reverse needed
manual firstExplain place values, then mention std::stoi(s, nullptr, 2)
Reach for binary-to-decimal drills when base conversion and bit place values matter.
Quick check of loops, powers, and input validation.
Makes 1, 2, 4, 8… feel concrete with a famous 42 example.
Same idea extends to octal, hex, and custom bases.
Bits show up constantly in networking and hardware topics.
Fractional binary (after a point) needs a different place-value story.
Key benefit: one short problem that covers powers of two, string loops, validation, and O(k) reasoning.
Enter a binary string (0 and 1 only) and convert it to decimal.
Three complete C++ programs — place-value loop, std::stoi(..., nullptr, 2), and the doubling method. Click View Output to reveal sample console results.
Powers of two from the right — the interview classic.
Validate bits, walk right-to-left, and add a power of 2 for every 1 (no std::pow).
#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;
} After validation, the loop starts at the rightmost bit with weight 1. Each 1 contributes the current power of two; zeros are skipped. Doubling the weight avoids std::pow.
Same answer with the built-in parser.
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;
} std::stoi(bits, nullptr, 2) interprets the string in base 2. Keeping your own validation gives clearer error messages than a bare std::invalid_argument.
Horner / doubling form — no reverse needed.
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;
} Each step shifts the previous total one bit left (multiply by 2) and adds the next bit. Leading zeros do not change the value — 00101 is still 5.
Reject empty strings and any character that is not 0 or 1.
Right-to-left with powers, left-to-right with doubling, or call std::stoi(s, nullptr, 2).
Add each 1-bit’s contribution into a running total.
Return the total — that is the base-10 value of the binary string.
101010Trace the place-value method from the right. Positions: 0 … 5.
| Bit (right→left) | Power | Contribution | total |
|---|---|---|---|
0 | 0 | 0 | 0 |
1 | 1 | 2 | 2 |
0 | 2 | 0 | 2 |
1 | 3 | 8 | 10 |
0 | 4 | 0 | 10 |
1 | 5 | 32 | 42 |
Final decimal: 42 (= 32 + 8 + 2).
Where binary-to-decimal conversion shows up beyond the interview prompt.
Tests place value, loops, and validation together.
Example: write BinaryToDecimal(s).
Makes 1, 2, 4, 8… memorable with 101010 → 42.
Example: chalkboard bit positions.
Some tools store compact bit masks as binary text.
Example: parse a permission bit string.
Same place-value idea with different bases.
Example: std::stoi(s, nullptr, 16) for hex.
Argue O(k) from the bit length convincingly.
Example: “how many loop iterations?”
C++ int/long long can overflow; use a big-integer library for huge bit strings.
Example: discuss fixed-width overflow.
Pro Tip: keep validation in one helper so manual, doubling, and built-in paths share the same rules.
Why this pattern works well in interviews and classwork.
Place values are exactly what the loop computes.
std::stoi(s, nullptr, 2) keeps application code short after you know the theory.
A few integers suffice — O(1) extra space beyond the input string.
Empty / invalid-character cases give interviewers easy follow-ups.
Pro Tip: say “rightmost bit is 20” before coding — it prevents off-by-one power mistakes.
Small habits that keep binary conversion interview-ready.
Check non-empty and only 0/1 characters first.
In interviews, show the manual sum before std::stoi(s, nullptr, 2).
Trim leading/trailing spaces so accidental spaces do not fail validation.
Assert the result is 42 — a fast golden test.
They are valid padding; do not strip them as invalid.
Pro Tip: dry-run 101010 on paper once — it locks in right-to-left powers faster than guessing.
Mistakes that commonly break binary-to-decimal solutions.
Treating the leftmost bit as 20 reverses place values.
→ Rightmost bit is power 0 for the classic method.
Digits like 2 or letters produce wrong results or cryptic errors.
→ Reject anything outside {0, 1} early.
std::stoi("101010") without base 2 reads it as decimal one-hundred-one-thousand…
→ Always pass base 2: std::stoi(bits, nullptr, 2).
Padding zeros are valid binary.
→ Allow them; they do not change the value.
An empty string should error, not convert to 0 silently in every design.
→ Decide the policy and document it.
Check these inputs before calling the solution done.
Reject strings like 1021 or 10a1.
Return a clear error instead of converting.
00101 is still valid and equals 5.
Smallest non-empty cases — return 0 or 1.
int/long long can overflow; JS live preview is capped for safety.
Trim spaces before validating characters.
Handy follow-ups interviewers sometimes ask.
std::stoi(s, nullptr, radix) works for any base from 2 to 36.Try these variations to lock in the pattern.
1021 and empty string00101std::stoi(s, nullptr, 2)std::stoi(bits, nullptr, 2) second.Quick Takeaway: sum 2i for each 1-bit (or call std::stoi(bits, nullptr, 2)) after validating the string.
| Program | Time | Extra space |
|---|---|---|
| Manual loop over bits | O(k) | O(1) |
std::stoi(bits, nullptr, 2) | O(k) | O(1) |
| Doubling method | O(k) | O(1) |
Binary-to-decimal conversion is a clean place-value exercise: validate the bits, then sum powers of two (or use std::stoi(s, nullptr, 2)). Master the manual loop first, then the doubling and built-in shortcuts.
Practice the three examples above, then continue to common divisors for another classic number-theory warm-up.
Always validate 0/1 input, remember the rightmost bit is 20, and state O(k) for k bits.
std::stoi(bits, nullptr, 2) as a shortcutstd::stoi(bits) without radix 2Convert base 2 the interview-friendly way.
Sum 2^i for 1-bits
DefinitionRightmost is 2^0
MathOnly 0 and 1
Guardstd::stoi(s, nullptr, 2)
CodeO(k) time
AnalysisBinary 101010 means 32 + 8 + 2, so its decimal value is 42.
Learn how to find all positive integers that divide two numbers evenly.
9 people found this page helpful