In PHP, the bindec() function is used to convert a binary string into a decimal number. Its basic usage is simple: pass in a pure binary string (composed of 0s and 1s), and it will return the corresponding decimal integer.
For example:
<?php
echo bindec('1011'); // Outputs 11
?>
However, if the binary string contains spaces, the bindec() function does not support it by default. It will start parsing the string from the beginning and stop when it encounters any non-0 or non-1 characters, meaning spaces will cause incorrect results, or even return 0.
Example:
<?php
echo bindec('101 1'); // Outputs 5, because parsing stops when it encounters the space, effectively interpreting '101'
?>
As seen, the space prevents bindec() from correctly parsing the entire binary data.
If your binary string contains spaces and you want to correctly convert it, you can first use PHP's string manipulation functions to remove the spaces and then pass the cleaned string to bindec().
Example:
<?php
$binaryWithSpaces = '101 1101 001';
$cleanBinary = str_replace(' ', '', $binaryWithSpaces);
$decimalValue = bindec($cleanBinary);
echo $decimalValue;
?>
Here, we use str_replace() to remove all spaces before calling bindec(), ensuring that the input is a pure binary string.
If your string contains other whitespace characters (such as tabs \t, newline characters \n, etc.), it’s recommended to use preg_replace() to remove all whitespace:
<?php
$binaryWithWhitespace = "101\t1101\n001";
$cleanBinary = preg_replace('/\s+/', '', $binaryWithWhitespace);
$decimalValue = bindec($cleanBinary);
echo $decimalValue;
?>
This ensures the binary string has no whitespace characters, allowing bindec() to parse it accurately.
The bindec() function does not support binary strings with spaces or other whitespace characters.
Before using bindec(), make sure to remove all whitespace characters from the input string.
You can use str_replace(' ', '', $str) to remove spaces, or the more powerful preg_replace('/\s+/', '', $str) to remove all whitespace characters.
Processing a clean, pure binary string ensures that bindec() will correctly return the decimal value.