PHP dechex() function


The dechex() function in PHP is used to convert a decimal (base 10) number into its hexadecimal (base 16) representation. This function is useful in various applications, such as color manipulation, low-level programming, and network programming, where hexadecimal notation is commonly used.

Syntax:

dechex(int $number): string
  • $number: The decimal number to be converted. This must be an integer.
  • Return Value: Returns the hexadecimal representation of the given decimal number as a string. The result will be in lowercase letters.

Example 1: Basic Usage

<?php echo dechex(255); ?>

Output:

ff

Explanation: The decimal number 255 is converted to its hexadecimal equivalent, which is ff.

Example 2: Conversion of Larger Numbers

<?php echo dechex(4095); ?>

Output:

fff

Explanation: The decimal number 4095 is represented in hexadecimal as fff.

Example 3: Negative Numbers

<?php echo dechex(-15); ?>

Output:

fffffffffffffff1

Explanation: When a negative number is provided, PHP converts it to its two's complement hexadecimal representation. Here, -15 is represented as fffffffffffffff1 in a 64-bit format.

Example 4: Zero

<?php echo dechex(0); ?>

Output:

0

Explanation: The hexadecimal representation of 0 is simply 0.

Key Points:

  • Input Type: The input for dechex() must be an integer. If a non-integer value is provided, it will be converted to an integer.
  • Negative Numbers: The function does not throw an error for negative numbers; instead, it returns their two's complement representation in hexadecimal format.
  • Output Format: The output is in lowercase. If uppercase letters are desired, you can use the strtoupper() function to convert the result.

Example of Practical Use:

<?php $decimalNumber = 345; $hexadecimalRepresentation = dechex($decimalNumber); echo "The hexadecimal representation of $decimalNumber is: $hexadecimalRepresentation\n"; // Example of using in color representation $red = 255; $green = 0; $blue = 128; $hexColor = dechex($red) . dechex($green) . dechex($blue); echo "Hexadecimal color representation: #$hexColor\n"; ?>

Output:

The hexadecimal representation of 345 is: 159 Hexadecimal color representation: #ff0080

Explanation: In this example, dechex() is used to convert a decimal number to its hexadecimal representation and to create a hexadecimal color code from RGB values.

In summary, dechex() is a useful PHP function for converting decimal numbers into hexadecimal format, making it essential for applications that involve hexadecimal notation, such as color codes and low-level data manipulation.