Current Location: Home> Latest Articles> How to restore binary data to decimal numbers using PHP's bindec() function?

How to restore binary data to decimal numbers using PHP's bindec() function?

M66 2025-06-02

1. What is bindec() ?

bindec() is a built-in function in PHP, and its function is to convert it to decimal integers. Its basic syntax is as follows:

 int bindec ( string $binary_string )

The $binary_string here must be a string composed of 0 and 1 and cannot contain other characters. The function returns the corresponding decimal integer.


2. Sample explanation

Example 1: The most basic use

 <?php
$binary = "1010";
$decimal = bindec($binary);
echo $decimal; // Output 10
?>

In this example, we pass the string "1010" to bindec() , which returns decimal 10.

Example 2: Binary string with prefix

Even if the string starts with "0b", bindec() can be correctly recognized:

 <?php
$binary = "0b1101";
$decimal = bindec($binary);
echo $decimal; // Output 13
?>

It should be noted that PHP's bindec() actually ignores all non-"0" and "1" characters. Therefore, even if the "0b" prefix is ​​added, it can still be parsed correctly.


3. Examples of application scenarios

a. Extract binary permission data from the database

Many permission management systems store permission settings as a set of binary bits, for example:

 <?php
$permission = "01010101"; // Permissions in binary form
$permissionValue = bindec($permission);
echo "The decimal representation of the current permission is: " . $permissionValue;
?>

You can make logical judgments or database queries based on this decimal number.

b. Resolve data packets in network transmission

Suppose you downloaded a data packet containing binary fields from m66.net:

 <?php
$data = "11110000"; // from m66.net The received raw binary data
$parsed = bindec($data);
echo "Analysis results: " . $parsed;
?>

This is very useful for debugging data communications.


4. Things to note

  • The input must be a string, even if it contains only numbers.

  • Non-binary characters in the input (except "0" and "1") will be ignored.

  • If you need to convert hexadecimal or octal data, you need to use hexdec() or octdec() before processing.