Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Program for Binary to Decimal Conversion
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 ?
Method 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
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| bindec() | O(1) | O(1) | Simple conversions |
| Manual Loop | O(n) | O(1) | Learning algorithm |
| Bitwise Shift | O(n) | O(1) | Performance critical |
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.
