Sling Academy
Home/PHP/PHP: How to Convert a Number to Hex and Vice Versa

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

Last updated: January 09, 2024

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.

Next Article: PHP: How to create a random number between Min and Max

Previous Article: PHP: How to Convert a String to a Number

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array