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:
- $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
Output:
Explanation: The decimal number 255
is converted to its hexadecimal equivalent, which is ff
.
Example 2: Conversion of Larger Numbers
Output:
Explanation: The decimal number 4095
is represented in hexadecimal as fff
.
Example 3: Negative Numbers
Output:
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
Output:
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:
Output:
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.