Convert Binary to Decimal in PHP
What you’ll learn
- Binary place value math.
- Two PHP methods: digit peel and string Horner.
- Validation, edge cases, and complexity.
Overview
Convert a binary pattern to decimal using powers of two.
Prerequisites
Loops, strings, and integer operations.
- PHP
while/forand arithmetic. - Basic understanding of binary digits 0/1.
What does binary to decimal mean?
Each bit at position i contributes bit * 2^i. Add contributions to get decimal.
Expanded form
101010₂ = 1*2⁵ + 1*2³ + 1*2¹ = 42.
Intuition
1010₂10
111₂7
Live preview
Algorithm
Goal: convert binary to decimal.
1
Initialize value = 0.
2
Read each bit and validate.
3
Update value using power-of-two or Horner.
📜 Pseudocode
Pseudocode
value = 0
for each bit in binaryString:
if bit not 0/1: error
value = value*2 + bit1
Digit peel from integer form
php
<?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 binaryDigitsToDecimal(101010); // 42
?>2
Horner method on string
php
<?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("101010"); // 42
?>Optimization
Horner form is concise and fast.
Validate early to avoid wrong results.
❓ FAQ
Add powers of 2 where bit is 1, or scan left to right with value = value*2 + bit.
Ensure every character is either 0 or 1 before conversion.
If binary has k bits, conversion takes O(k) time and O(1) extra space.
Yes. Very long binary strings can exceed integer range.
🔄 Input / output examples
| Binary | Decimal |
|---|---|
101010 | 42 |
111 | 7 |
102 | Error |
Edge cases and pitfalls
Digits
Invalid characters
Reject anything other than 0/1.
Overflow
Very long strings
Huge values may exceed integer limits.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Digit peel / Horner | O(k) | O(1) |
Summary
- Binary to decimal uses powers of two.
- Use validation and O(k) loop.
- Horner method is clean and practical.
Did you know?
101010 in binary equals 42 in decimal because only the 32, 8, and 2 positions are turned on.
9 people found this page helpful
