In PHP, the bindec() function is used to convert a binary string into its corresponding decimal value. Its definition is very simple:
int|float bindec(string $binary_string)
However, many developers have a question when using it: does the bindec() function return an integer type (int) or a floating-point type (float)? The answer to this question is not entirely intuitive, so let's break it down in detail below.
<?php
$binary = "1010"; // Binary number, equivalent to decimal 10
$decimal = bindec($binary);
echo $decimal; // Output: 10
echo gettype($decimal); // Output: integer
?>
From this example, we can see that bindec() returns an integer type.
The range of PHP's integer type (int) differs between 32-bit and 64-bit systems:
On a 32-bit system, the maximum integer is 2,147,483,647 (about 2 billion).
On a 64-bit system, the maximum integer is 9,223,372,036,854,775,807 (about 9 quintillion).
If the value obtained from converting a binary string exceeds the integer range of the system, PHP will automatically convert the return value to a floating-point number (float). This happens because PHP's integer type has size limitations, while the floating-point type can represent a wider range of numbers (though it may lose precision).
Here's an example:
<?php
// Binary number greater than 2147483647 on a 32-bit system
$binary = "11111111111111111111111111111111"; // 32 ones, equal to 4294967295, exceeding the 32-bit integer range
$decimal = bindec($binary);
echo $decimal . "\n"; // Output: 4294967295
echo gettype($decimal) . "\n"; // On a 32-bit system, output: double (PHP displays float as double)
?>
On a 32-bit system, this value exceeds the maximum integer range, so it returns a floating-point number.
When the decimal value corresponding to the binary number is within the integer range, bindec() returns an int type.
When the value exceeds the integer range, bindec() returns a float type.
On 64-bit systems, only very large binary numbers will return a float, whereas the conversion range is smaller on 32-bit systems.
The bindec() function simply converts the binary string as an unsigned number. The binary string has no concept of a positive or negative sign. If you need to handle signed binary numbers, you will need to implement the conversion logic manually.
For more detailed information about bindec(), please visit the PHP Manual.