Binary to decimal conversion is the process of converting a binary number (base-2 number using only 0s and 1s) into its equivalent decimal number (base-10 form).
In this article, we will learn how to convert binary numbers to decimal form in PHP using different approaches.
How Binary to Decimal Conversion Works
To convert a binary number to decimal, multiply each binary digit by 2 raised to the power of its position (starting from 0 on the right), then sum all results ?
Binary to Decimal Conversion: 1011 Position: 3 2 1 0 Binary: 1 0 1 1 Calculation: 1×2³ 0×2² 1×2¹ 1×2? = 8 = 0 = 2 = 1 Result: 8 + 0 + 2 + 1 = 11Method 1: Using Built-in bindec() Function
PHP provides the bindec() function to convert binary numbers directly to decimal ?
<?php $binary = "101"; // Convert binary to decimal using bindec() $decimal = bindec($binary); echo "Binary $binary = Decimal $decimal"; ?>
Binary 101 = Decimal 5
Method 2: Manual Conversion Using Loop
This approach manually calculates the decimal value by iterating through each binary digit ?
<?php
$binary = "1011";
$decimal = 0;
$length = strlen($binary);
// Loop through each digit from right to left
for ($i = 0; $i < $length; $i++) {
$digit = $binary[$length - $i - 1];
$decimal += $digit * pow(2, $i);
}
echo "Binary $binary = Decimal $decimal";
?>
Binary 1011 = Decimal 11
Method 3: Using Bitwise Left Shift
This method uses bitwise operations for efficient conversion ?
<?php
function binaryToDecimalBitwise($binary) {
$decimal = 0;
for ($i = 0; $i < strlen($binary); $i++) {
$decimal = ($decimal << 1) + $binary[$i];
}
return $decimal;
}
$binary = "1111";
$decimal = binaryToDecimalBitwise($binary);
echo "Binary $binary = Decimal $decimal";
?>
Binary 1111 = Decimal 15
Comparison of Methods
Conclusion
Use bindec() for simple binary to decimal conversions in PHP. For educational purposes or custom logic, implement manual conversion using loops or bitwise operations.