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 PHP 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, use a Horner loop, or call PHP’s bindec() / intval($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; bindec($s) for apps.
Very long bit strings can exceed PHP integer range — validate length.
In short: for each 1-bit at position i (from the right), add 2i — or just call bindec($bits).
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 |
|---|---|---|
| Digit peel / place value | Peel bits with % 10 and add weights | Best for showing interview math |
bindec($bits) | Built-in base-2 parse | Shortest production style |
| Goal | Pattern |
|---|---|
| Validate bits | preg_match('/[^01]/', $bits) must fail |
| Digit peel | $digit = $n % 10; $n = intdiv($n, 10) |
| Add place value | $value += $digit * $weight |
| Built-in convert | bindec($bits) or intval($bits, 2) |
| Horner / doubling | $value = $value * 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 PHP for real applications
2*total + bitLeft-to-right Horner form; no reverse needed
manual firstExplain place values, then mention bindec($s)
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 PHP programs — digit peel, bindec, and the Horner / doubling method. Click View Output to reveal sample console results.
Powers of two from the right — peel digits stored as an int.
Treat the binary pattern as a decimal-looking int (e.g. 101010), peel digits with % 10, and add place values.
<?php
function binaryDigitsToDecimal(int $binaryForm): int
{
$value = 0;
$weight = 1;
$n = $binaryForm;
while ($n > 0) {
$digit = $n % 10;
if ($digit !== 0 && $digit !== 1) return -1;
$value += $digit * $weight;
$n = intdiv($n, 10);
$weight *= 2;
}
return $value;
}
echo "Binary digits: 101010" . PHP_EOL;
echo "Decimal: " . binaryDigitsToDecimal(101010) . PHP_EOL;
?> Each loop peels the least-significant decimal digit of $n and treats it as a binary bit. $weight doubles each step (1, 2, 4, …). Invalid digits return -1.
Same answer with the built-in parser.
bindec()Validate first, then let PHP parse the base-2 string.
<?php
function binaryToDecimalBuiltin(string $bits): int
{
$bits = trim($bits);
if ($bits === '' || preg_match('/[^01]/', $bits)) {
return -1;
}
return (int) bindec($bits);
}
$binaryNumber = "101010";
echo "Binary: " . $binaryNumber . PHP_EOL;
echo "Decimal: " . binaryToDecimalBuiltin($binaryNumber) . PHP_EOL;
?> bindec($bits) interprets the string in base 2 (same idea as intval($bits, 2)). Keeping your own validation gives clearer error handling than relying on silent casting.
Horner / doubling form — no reverse needed.
For each bit from the left: $value = $value * 2 + $bit.
<?php
function binaryStringToDecimal(string $s): int
{
if ($s === '') return -1;
$value = 0;
for ($i = 0; $i < strlen($s); $i++) {
$ch = $s[$i];
if ($ch !== '0' && $ch !== '1') return -1;
$value = $value * 2 + ($ch === '1' ? 1 : 0);
}
return $value;
}
echo binaryStringToDecimal("1010") . PHP_EOL;
echo binaryStringToDecimal("00101") . PHP_EOL;
?> 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 bindec($s).
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: hexdec($s) or intval($s, 16) for hex.
Argue O(k) from the bit length convincingly.
Example: “how many loop iterations?”
PHP integers are platform-sized; very long bit strings can overflow.
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.
bindec($s) 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 bindec($s).
Call trim() 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.
intval("101010") without base 2 reads it as decimal one-hundred-one-thousand…
→ Use bindec($bits) or intval($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.
Huge values can exceed PHP int limits; the JS live preview is also capped for safety.
Trim spaces before validating characters.
Handy follow-ups interviewers sometimes ask.
intval($s, $base) works for bases from 2 to 36; helpers like hexdec / octdec also exist.Try these variations to lock in the pattern.
1021 and empty string00101bindec($s)bindec($bits) second.Quick Takeaway: sum 2i for each 1-bit (or call bindec($bits)) after validating the string.
| Program | Time | Extra space |
|---|---|---|
| Digit peel / place-value loop | O(k) | O(1) |
Built-in bindec($bits) | O(k) | O(1) |
| Horner / 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 bindec($s)). 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.
bindec($bits) as a shortcutintval($bits) without base 2Convert base 2 the interview-friendly way.
Sum 2^i for 1-bits
DefinitionRightmost is 2^0
MathOnly 0 and 1
Guardbindec($s)
CodeO(k) time
Analysis101010 in binary equals 42 in decimal because only the 32, 8, and 2 positions are turned on.
Learn how to find all positive integers that divide two numbers evenly.
9 people found this page helpful