In PHP, the bindec function is commonly used to convert a binary string into a decimal number. Its basic usage is quite simple:
<?php
$binaryString = "1010";
$decimal = bindec($binaryString);
echo $decimal; // Outputs 10
?>
However, sometimes we encounter binary strings with a "0b" prefix, such as "0b1010". So, how does the bindec function handle such strings with prefixes? This article will analyze this in detail.
According to the official documentation, the bindec function parses all binary digits ('0' or '1') in a string from left to right until it encounters the first non-binary character. It then converts the parsed portion into a decimal integer.
In short, bindec only cares about valid binary digits in the string. Any other character causes the parsing to stop early.
We can verify this with some example code:
<?php
echo bindec("1010") . "\n"; // Outputs 10
echo bindec("0b1010") . "\n"; // Outputs 0
echo bindec("b1010") . "\n"; // Outputs 0
echo bindec("01010") . "\n"; // Outputs 10
?>
From the results, we can see:
"1010" is correctly parsed as 10.
"0b1010" returns 0 because the function encounters the first character '0' as a valid binary digit, but the next character 'b' is not valid, causing parsing to stop and only the '0' part being parsed, which is decimal 0.
"b1010" directly returns 0 because the first character 'b' is not a valid binary digit, leading to a parsing failure.
"01010" is a valid binary string, and the result is 10.
This shows that bindec does not support binary strings with the "0b" prefix. It only parses the valid binary part before encountering any non-binary characters, stopping at the first invalid character.
If you need to parse a binary string with the "0b" prefix, you can remove the prefix before calling bindec.
Example code:
<?php
function bindec_with_prefix(string $binaryStr): int {
// If the string starts with '0b' or '0B', remove the prefix
if (stripos($binaryStr, '0b') === 0) {
$binaryStr = substr($binaryStr, 2);
}
return bindec($binaryStr);
}
<p>echo bindec_with_prefix("0b1010"); // Outputs 10<br>
echo "\n";<br>
echo bindec_with_prefix("1010"); // Outputs 10<br>
?><br>
By doing this, whether the string has a "0b" prefix or not, it will be correctly converted to a decimal number.
The bindec function in PHP only accepts pure binary strings (composed of '0' and '1'). Parsing stops when a non-binary character is encountered.
Adding a "0b" prefix to a binary string will cause bindec to return an incorrect result (usually 0), because it will stop at the 'b' character.
To correctly parse strings with a "0b" prefix, remove the prefix before calling bindec.
Understanding this can help you avoid unnecessary errors and debugging time when dealing with binary string conversions.