In PHP, converting between binary and decimal is very convenient and mainly relies on two built-in functions: bindec() and decbin(). These two functions are used to convert binary to decimal and decimal to binary, respectively. This article will provide a detailed introduction to how these functions work and how to use them together for bidirectional data conversion.
The bindec() function is used to convert a binary number (in string form) to a decimal number. It accepts a string parameter that only contains the characters 0 and 1, and returns the corresponding decimal integer.
Syntax:
int bindec ( string $binary_string )
Example:
<?php
$binary = "1101"; // Binary string
$decimal = bindec($binary);
echo $decimal; // Outputs 13
?>
The decbin() function is used to convert a decimal integer to a binary string. It accepts an integer as a parameter and returns the corresponding binary string.
Syntax:
string decbin ( int $number )
Example:
<?php
$decimal = 13;
$binary = decbin($decimal);
echo $binary; // Outputs 1101
?>
Below is a complete example showing how to use these two functions for mutual conversion 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>
?><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 computation or display, conversion to decimal is necessary.
Numerical Processing: In low-level operations or algorithms, frequent conversion between binary and decimal is required.
User Input: Users may enter numbers in binary form, which need to be converted to decimal for logical processing in the program.
The bindec() and decbin() functions only support conversion of positive integers. Negative number conversion requires additional handling.
The binary string input must be valid; otherwise, bindec() will return 0.
Very long binary strings may cause results to exceed the integer range; consider using the GMP extension for handling large numbers.