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 Python 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 Python’s int(bits, 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; int(s, 2) for apps.
Long bit strings stay exact — limited by memory, not overflow.
In short: for each 1-bit at position i (from the right), add 2i — or just call int(bits, 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 binary_to_decimal(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 |
int(bits, 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 ch in reversed(bits) |
| Add place value | total += 2 ** power |
| Built-in convert | int(bits, 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 Python for real applications
2*total + bitLeft-to-right Horner form; no reverse needed
manual firstExplain place values, then mention int(s, 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 Python programs — place-value loop, int(..., 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 2 ** power for every 1.
def binary_to_decimal_manual(bits: str) -> int:
bits = bits.strip()
if not bits or any(ch not in "01" for ch in bits):
raise ValueError("Binary string must contain only 0 and 1")
total = 0
power = 0
for ch in reversed(bits):
if ch == "1":
total += 2 ** power
power += 1
return total
binary_number = "101010"
decimal_number = binary_to_decimal_manual(binary_number)
print(f"Binary: {binary_number}")
print(f"Decimal: {decimal_number}") After validation, reversed(bits) makes the rightmost bit power 0. Each 1 contributes 2 ** power; zeros are skipped.
Same answer with the built-in parser.
int(..., 2)Validate first, then let Python parse the base-2 string.
def binary_to_decimal_builtin(bits: str) -> int:
bits = bits.strip()
if not bits or any(ch not in "01" for ch in bits):
raise ValueError("Binary string must contain only 0 and 1")
return int(bits, 2)
binary_number = "101010"
print(f"Binary: {binary_number}")
print(f"Decimal: {binary_to_decimal_builtin(binary_number)}") int(bits, 2) interprets the string in base 2. Keeping your own validation gives clearer error messages than a bare ValueError from int.
Horner / doubling form — no reverse needed.
For each bit from the left: total = total * 2 + bit.
def binary_to_decimal_doubling(bits: str) -> int:
bits = bits.strip()
if not bits or any(ch not in "01" for ch in bits):
raise ValueError("Binary string must contain only 0 and 1")
total = 0
for ch in bits:
total = total * 2 + (1 if ch == "1" else 0)
return total
print(binary_to_decimal_doubling("1010"))
print(binary_to_decimal_doubling("00101")) 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 int(s, 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 binary_to_decimal(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: int(s, 16) for hex.
Argue O(k) from the bit length convincingly.
Example: “how many loop iterations?”
Python keeps long conversions exact; other languages may not.
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.
int(s, 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 int(s, 2).
Call strip() 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.
int("101010") without base 2 reads it as decimal one-hundred-one-thousand…
→ Always pass base 2: int(bits, 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.
Integers grow; JS live preview is capped for safety.
Trim spaces before validating characters.
Handy follow-ups interviewers sometimes ask.
int(s, base) works for any base from 2 to 36.Try these variations to lock in the pattern.
1021 and empty string00101int(s, 2)int(bits, 2) second.Quick Takeaway: sum 2i for each 1-bit (or call int(bits, 2)) after validating the string.
| Program | Time | Extra space |
|---|---|---|
| Manual loop over bits | O(k) | O(1) |
Built-in int(bits, 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 int(s, 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.
int(bits, 2) as a shortcutint(bits) without base 2Convert base 2 the interview-friendly way.
Sum 2^i for 1-bits
DefinitionRightmost is 2^0
MathOnly 0 and 1
Guardint(s, 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