PHP decbin() function


The decbin() function in PHP is used to convert a decimal (base 10) number into its binary (base 2) representation. This function is particularly useful in applications involving low-level programming, bit manipulation, and binary arithmetic.

Syntax:

decbin(int $number): string
  • $number: The decimal number to be converted. This should be an integer.
  • Return Value: Returns the binary representation of the given decimal number as a string.

Example 1: Basic Usage

<?php echo decbin(10); ?>

Output:

1010

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

Example 2: Conversion of Larger Numbers

<?php echo decbin(255); ?>

Output:

11111111

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

Example 3: Negative Numbers

<?php echo decbin(-5); ?>

Output:

11111111111111111111111111111011

Explanation: When a negative number is provided, PHP uses the two's complement representation for binary numbers. The output shows the 32-bit binary representation of -5.

Example 4: Zero

<?php echo decbin(0); ?>

Output:

0

Explanation: The binary representation of 0 is simply 0.

Key Points:

  • Input Type: The input for decbin() must be an integer. If a non-integer value is provided, it will be converted to an integer, which might lead to unexpected results.
  • Negative Numbers: The function does not throw an error for negative numbers; instead, it provides the two's complement representation.
  • Use Cases: This function is useful in various scenarios, including binary arithmetic operations, bit manipulation, and when working with low-level data structures.

Example of Practical Use:

<?php $decimalNumber = 13; $binaryRepresentation = decbin($decimalNumber); echo "The binary representation of $decimalNumber is: $binaryRepresentation\n"; // Example of using in bitwise operations $bitwiseResult = $decimalNumber & 7; // Bitwise AND with 7 (binary: 111) echo "Bitwise AND result of $decimalNumber and 7 is: " . decbin($bitwiseResult) . "\n"; ?>

Output:

The binary representation of 13 is: 1101 Bitwise AND result of 13 and 7 is: 1101

Explanation: This example converts a decimal number to its binary representation and demonstrates how it can be used in bitwise operations.

In summary, decbin() is a handy PHP function for converting decimal numbers into binary format, making it useful in programming contexts that require binary data manipulation and representation.