PHP: How to Convert a Number to Hex and Vice Versa

Updated: January 9, 2024 By: Guest Contributor Post a comment

Overview

In this tutorial, we explore how to convert numbers into hexadecimal representations and vice versa using PHP, bridging the fundamental gap between human-readable numbers and machine-friendly notation.

Understanding hex (hexadecimal) notation and conversion techniques can be invaluable in various computing contexts, such as web design, color references, and low-level data processing. This guide provides an extensive look at how to perform num-to-hex conversions using PHP, equip with progressively in-depth examples.

Converting Numbers to Hexadecimal in PHP

PHP offers native functions for converting numeric values to hexadecimal format. Utilizing dechex(), which takes an integer as input and returns a string representing the number in hexadecimal format:

$number = 255;
$hex = dechex($number);
echo $hex; // Outputs: 'ff'

This is great for converting positive integers, but what if we need to handle negative numbers or larger integers?

Handling Larger and Negative Numbers

For large integers that exceed the maximum value for a 32-bit integer, PHP’s dechex() may not yield the expected outcome:

$largeNumber = 4294967295;
$hexLarge = dechex($largeNumber);
echo $hexLarge; // Outputs: 'ffffffff'

Negative integers require a little bit of additional logic as they are two’s complement on most systems:

$negative = -255;
$hexNegative = dechex($negative);
echo $hexNegative; // PHP Warning:  dechex() expects parameter 1 to be positive

We’ll cover handling of such scenarios later in the ‘Advanced Techniques’ section.

Converting Hexadecimal to Numbers

Reversing the process—converting hexadecimal strings back to decimal integers—is done with the hexdec() PHP function:

$hex = 'ff';
$number = hexdec($hex);
echo $number; // Outputs: 255

Handling larger hexadecimal strings, that result in numbers exceeding PHP’s integer range, will yield a float as the converted value:

$hexLarge = '1ffffffff';
$numberLarge = hexdec($hexLarge);
echo $numberLarge; // Outputs a float since it exceeds PHP's integer range

Intermediate Techniques

What if you need to ensure that your hex string consistently has a particular number of characters, such as leading zeros for RGB colors? This is where sprintf() function is handy:

$number = 255;
$hex = sprintf("%02x", $number);
echo $hex; // Outputs: 'ff'

Situationally, we might also want the hex string to be represented in uppercase. This requires a minor adjustment:

echo strtoupper($hex); // Outputs: 'FF'

Advanced Techniques

When working with negative numbers or numbers larger than 32 bits, you will need to circumvent PHP’s built-in functions’ limitations:

$number = -255;
$result = unpack("H*", pack("l", $number));
$hexNegative = $result[1];
echo $hexNegative; // Outputs a valid hex string

For unsigned long representations:

$number = 4294967295;
$hex = sprintf('%08x', $number);
echo $hex; // Outputs: 'ffffffff'

Note that these techniques may require additional transformations depending on the system architecture.

Hexadecimal Arithmetic and Bitwise Operations

Integrating hexadecimal values in mathematical operations and algorithms necessitates understanding bitwise operations on a more profound level. PHP offers several operators for this purpose: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), and ~ (bitwise NOT).

$firstHex = 0x1A;
$secondHex = 0x0F;
$result = $firstHex & $secondHex;
echo dechex($result);  // Outputs: 'a'

Conclusion

With the concepts and code examples we’ve traversed, you should be equipped to handle various hexadecimal conversion tasks in PHP. While most cases are solved by built-in functions, understanding the underpinnings of hex representation will empower you to solve more complex problems as they arise.