0
0
PhpHow-ToBeginner · 2 min read

PHP How to Convert Binary to Decimal Number

In PHP, convert binary to decimal using bindec() function like bindec('1010') which returns 10.
📋

Examples

Input1010
Output10
Input11111111
Output255
Input0
Output0
🧠

How to Think About It

To convert binary to decimal, think of each binary digit as a power of 2 starting from the right (0th power). Multiply each digit by 2 raised to its position index and add all results to get the decimal number.
📐

Algorithm

1
Get the binary number as a string input.
2
Start from the rightmost digit and assign it position 0.
3
For each digit, multiply it by 2 raised to the power of its position.
4
Add all these values together to get the decimal number.
5
Return the decimal number.
💻

Code

php
<?php
$binary = '1010';
$decimal = bindec($binary);
echo $decimal;
?>
Output
10
🔍

Dry Run

Let's trace binary '1010' through the code

1

Input binary string

binary = '1010'

2

Convert using bindec

bindec('1010') calculates decimal

3

Output decimal

decimal = 10

Binary DigitPositionValue (digit * 2^position)
000 * 2^0 = 0
111 * 2^1 = 2
020 * 2^2 = 0
131 * 2^3 = 8
💡

Why This Works

Step 1: Using bindec function

PHP's bindec() converts a binary string directly to decimal by internally calculating powers of 2.

Step 2: Binary digit positions

Each binary digit represents a power of 2 based on its position from right to left starting at 0.

Step 3: Summing values

Multiplying each digit by its power of 2 and summing all gives the decimal equivalent.

🔄

Alternative Approaches

Manual calculation with loop
php
<?php
$binary = '1010';
$decimal = 0;
$length = strlen($binary);
for ($i = 0; $i < $length; $i++) {
    $bit = $binary[$length - $i - 1];
    $decimal += $bit * pow(2, $i);
}
echo $decimal;
?>
This method shows the calculation steps but is slower and more code than bindec.
Using base_convert function
php
<?php
$binary = '1010';
$decimal = base_convert($binary, 2, 10);
echo $decimal;
?>
base_convert converts between bases but returns a string; bindec returns an integer.

Complexity: O(n) time, O(1) space

Time Complexity

The conversion scans each binary digit once, so time grows linearly with input length.

Space Complexity

Only a few variables are used, so space is constant regardless of input size.

Which Approach is Fastest?

Using bindec() is fastest and simplest; manual loops are slower but educational.

ApproachTimeSpaceBest For
bindec()O(n)O(1)Quick and easy conversion
Manual loopO(n)O(1)Learning how conversion works
base_convert()O(n)O(1)Converting between any bases
💡
Use PHP's built-in bindec() for quick and reliable binary to decimal conversion.
⚠️
Forgetting that binary input must be a string, not an integer, to avoid unexpected results.