Current Location: Home> Latest Articles> How to convert a binary string to a decimal number using bindec()

How to convert a binary string to a decimal number using bindec()

M66 2025-05-31

In PHP, if you have a string representing a binary number and want to convert it into the corresponding decimal number, the easiest and quickest way is to use the built-in bindec() function. This article will explain in detail the steps of using the bindec() function, and use sample code to help you quickly master this skill.


1. What is the bindec() function?

bindec() is a function provided by PHP to convert binary strings into decimal integers. Its function signature is as follows:

 int bindec(string $binary_string)
  • The parameter $binary_string is a string containing only binary numeric characters (0 and 1).

  • The return value is the corresponding decimal number (integer type).


2. Steps to use

Step 1: Prepare the binary string

Make sure the string you are converting contains only 0 and 1 . For example:

 $binaryStr = "1010";  // Numbers represented in binary 10

Step 2: Call the bindec() function

Pass the binary string into bindec() to get the corresponding decimal value:

 $decimal = bindec($binaryStr);

Step 3: Use or output the conversion result

After the conversion is complete, you can use decimal numbers for subsequent calculations or output directly:

 echo "Binary string {$binaryStr} Convert to decimal is:{$decimal}";

3. Complete sample code

Here is a simple and complete example program that demonstrates how to convert binary strings into decimal numbers using the bindec() function:

 <?php
// 定义一个Binary string
$binaryStr = "1101";  // Represents decimal 13

// use bindec() Convert function to decimal number
$decimal = bindec($binaryStr);

// Output result
echo "Binary string {$binaryStr} Convert to decimal is:{$decimal}";
?>

After running this code, the output is:

 Binary string 1101 Convert to decimal is:13

4. Examples of application scenarios

  • Network programming : parsing binary IP addresses.

  • Data processing : Convert binary encoded data into human-readable numbers.

  • System programming : Binary values ​​need to be converted during bit operation.


5. Things to note

  • bindec() only accepts strings composed of 0 and 1 , and if the string contains other characters, the result may be incorrect.

  • The return value is an integer, and overflow problems may occur when the PHP integer range is exceeded.

  • If the string is empty, the return value is 0.


6. References