Current Location: Home> Latest Articles> How to Use the bindec() Function in PHP? Basic Usage and Detailed Explanation

How to Use the bindec() Function in PHP? Basic Usage and Detailed Explanation

M66 2025-06-12

In PHP programming, it is often necessary to convert between different numeral systems. The bindec() function is specifically designed to convert binary strings into decimal numbers. This article will provide a detailed explanation of the bindec() function's usage, helping you understand and apply it better.


What is the bindec() Function?

The bindec() function is used to convert a string representing a binary number into its corresponding decimal integer. The "bin" in the function name represents binary, while "dec" represents decimal, so it essentially means "binary to decimal".

Function prototype:

int bindec(string $binary_string)
  • Parameters: $binary_string, a string containing only the characters 0 and 1, representing a binary number.

  • Return value: Returns the corresponding decimal integer.


Basic Usage Example of the bindec() Function

<?php
$binary = "1011";   // Binary number 1011, equal to decimal 11
$decimal = bindec($binary);
echo $decimal;      // Outputs 11
?>

Running the code above will output 11, as the binary 1011 is equal to the decimal number 11.


Detailed Explanation

  1. The input must be a binary string
    The bindec() function expects the input string to only contain the characters 0 and 1. If the string contains any other characters, PHP will ignore the first invalid character and all subsequent characters, processing only the valid part.

<?php
echo bindec("11012abc"); // Parses up to 1101, outputs 13
?>
  1. Handling empty strings
    If an empty string is passed, the return value will be 0.

  2. Supports long binary strings
    PHP's integer size limit depends on the platform (32-bit or 64-bit). Values exceeding the limit may result in inaccurate results.

  3. Comparison with other numeral system conversion functions


Practical Application Example

Suppose you receive a binary string from a web form and need to convert it to decimal for calculation:

<?php
if (isset($_GET['bin'])) {
    $binary_input = $_GET['bin'];
    $decimal_value = bindec($binary_input);
    echo "Binary {$binary_input} converted to decimal is {$decimal_value}";
}
?>

Access a URL like this:

http://m66.net/convert.php?bin=1101

The page will output:

Binary 1101 converted to decimal is 13

Summary

  • The bindec() function is a very practical tool in PHP for converting binary to decimal.

  • The input must be a string consisting of 0s and 1s, or it will only parse up to the first invalid character.

  • It is suitable for processing user input of binary numbers and converting them into values for subsequent calculations.

If you need to perform binary-to-decimal conversions in PHP, bindec() is a direct and efficient choice.