In PHP, converting between binary and decimal is very convenient, relying primarily on two built-in functions: bindec() and decbin(). These functions are used to convert binary to decimal and decimal to binary, respectively. This article will explain how to use these two functions and how to combine them for bidirectional data conversion.
The bindec() function is used to convert a binary number (in string format) to a decimal number. It takes a string parameter that only contains the characters 0 and 1, returning the corresponding decimal integer.
Syntax:
int bindec ( string $binary_string )
Example:
<?php
$binary = "1101"; // Binary string
$decimal = bindec($binary);
echo $decimal; // Output: 13
?>
The decbin() function converts a decimal integer to a binary string. It takes an integer as a parameter and returns the binary string corresponding to that integer.
Syntax:
string decbin ( int $number )
Example:
<?php
$decimal = 13;
$binary = decbin($decimal);
echo $binary; // Output: 1101
?>
Here is a complete example showing how to use these two functions to convert between binary and decimal:
<?php
// Define a binary string
$binaryStr = "101101";
<p>// Binary to Decimal<br>
$decimalNum = bindec($binaryStr);<br>
echo "Binary {$binaryStr} converted to decimal is: {$decimalNum}\n";</p>
<p>// Decimal to Binary<br>
$binaryConverted = decbin($decimalNum);<br>
echo "Decimal {$decimalNum} converted to binary is: {$binaryConverted}\n";<br>
?>
Output:
Binary 101101 converted to decimal is: 45
Decimal 45 converted to binary is: 101101
Data Storage and Transmission: Some systems store data as binary strings, and for calculations or display, they need to be converted to decimal numbers.
Numeric Processing: In some low-level operations or algorithms, it is necessary to frequently switch between binary and decimal.
User Input: Users might input numbers in binary form, which need to be converted to decimal for program logic processing.
bindec() and decbin() only support conversion of positive integers; negative number conversions require additional handling.
The input binary string must be valid, otherwise bindec() will return 0.
If the binary string is too long, it may exceed the integer range; consider using the GMP extension for handling large numbers.