PHP dechex() Function

The dechex() function converts a decimal number to its hexadecimal representation and returns it as a string. This function is particularly useful for color codes, memory addresses, and low-level programming operations.

Syntax

dechex ( int $number ) : string

Parameters

Parameter Description
number A decimal number to be converted to hexadecimal representation

Return Value

Returns a string containing the hexadecimal representation of the given decimal number.

Example 1: Basic Usage

Converting positive decimal numbers to hexadecimal ?

<?php
    echo dechex(10) . "<br>";
    echo dechex(255) . "<br>";
    echo dechex(16) . "<br>";
    echo dechex(1000);
?>
a
ff
10
3e8

Example 2: Negative Numbers

When converting negative numbers, the function returns the two's complement representation ?

<?php
    $arg = -10;
    $val = dechex($arg);
    echo "dechex(" . $arg . ") = " . $val . "<br>";
    
    echo "dechex(-1) = " . dechex(-1) . "<br>";
    echo "dechex(-255) = " . dechex(-255);
?>
dechex(-10) = fffffffffffffff6
dechex(-1) = ffffffffffffffff
dechex(-255) = ffffffffffffff01

Example 3: Practical Use Case

Converting RGB color values to hexadecimal format ?

<?php
    $red = 255;
    $green = 128;
    $blue = 64;
    
    $hexColor = "#" . str_pad(dechex($red), 2, "0", STR_PAD_LEFT) . 
                     str_pad(dechex($green), 2, "0", STR_PAD_LEFT) . 
                     str_pad(dechex($blue), 2, "0", STR_PAD_LEFT);
    
    echo "RGB($red, $green, $blue) = $hexColor";
?>
RGB(255, 128, 64) = #ff8040

Key Points

  • The function only accepts integer values; floating-point numbers are converted to integers first
  • Negative numbers return unsigned 64-bit hexadecimal representation
  • Use str_pad() to ensure consistent hex string length when needed
  • Available in all PHP versions (4.x, 5.x, 7.x, 8.x)

Conclusion

The dechex() function is essential for converting decimal numbers to hexadecimal strings. It's commonly used in color manipulation, bitwise operations, and when working with memory addresses or hash values.

Updated on: 2026-03-15T08:56:06+05:30

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements