PHP bindec() function


The bindec() function in PHP is used to convert a binary (base 2) number into its decimal (base 10) representation. This function is particularly useful when working with binary numbers, such as those used in low-level programming, bit manipulation, and network programming.

Syntax:

bindec(string $binary_string): int
  • $binary_string: A string containing the binary number to be converted. The string should consist only of characters 0 and 1.
  • Return Value: Returns the decimal representation of the given binary number as an integer.

Example 1: Basic Usage

<?php echo bindec('1010'); ?>

Output:

10

Explanation: The binary number 1010 is converted to its decimal equivalent, which is 10.

Example 2: Conversion of Larger Binary Numbers

<?php echo bindec('11111111'); ?>

Output:

255

Explanation: The binary number 11111111 is represented in decimal as 255.

Example 3: Binary with Leading Zeros

<?php echo bindec('00001010'); ?>

Output:

10

Explanation: Leading zeros do not affect the conversion; thus, 00001010 is also converted to 10.

Example 4: Invalid Binary String

<?php echo bindec('10102'); ?>

Output:

Warning: bindec(): Illegal binary string

Explanation: If the input string contains characters other than 0 and 1, PHP will issue a warning and treat the input as invalid.

Key Points:

  • Input Type: The input for bindec() should be a string containing only binary digits. If the string contains invalid characters, a warning will be generated.
  • Use Cases: This function is useful in various scenarios, including network programming, data encoding, and working with bit-level operations.

Example of Practical Use:

<?php $binaryNumber = '1101'; $decimalRepresentation = bindec($binaryNumber); echo "The decimal representation of binary $binaryNumber is: $decimalRepresentation\n"; // Example of using in bitwise operations $bitwiseResult = bindec('1100') & bindec('1010'); // Bitwise AND echo "Bitwise AND result of binary 1100 and 1010 is: " . decbin($bitwiseResult) . "\n"; ?>

Output:

The decimal representation of binary 1101 is: 13 Bitwise AND result of binary 1100 and 1010 is: 1000

Explanation: This example demonstrates how to convert a binary number to its decimal representation and shows how bindec() can be used in bitwise operations.

In summary, bindec() is a useful PHP function for converting binary numbers into decimal format, making it essential for applications that involve binary data manipulation and representation.