PHP hexdec() function


The hexdec() function in PHP is used to convert a hexadecimal (base 16) number into its decimal (base 10) representation. This function is useful in various applications, such as color manipulation in web development, low-level programming, and data encoding.

Syntax:

hexdec(string $hex_string): float|int
  • $hex_string: A string containing the hexadecimal number to be converted. The string can optionally include a 0x prefix (e.g., 0x1A).
  • Return Value: Returns the decimal representation of the given hexadecimal number as an integer or float, depending on the value.

Example 1: Basic Usage

<?php echo hexdec('1A'); ?>

Output:

26

Explanation: The hexadecimal number 1A is converted to its decimal equivalent, which is 26.

Example 2: Hexadecimal with Prefix

<?php echo hexdec('0xFF'); ?>

Output:

255

Explanation: The hexadecimal number FF, when prefixed with 0x, is converted to 255 in decimal.

Example 3: Larger Hexadecimal Numbers

<?php echo hexdec('1C8'); ?>

Output:

456

Explanation: The hexadecimal number 1C8 is converted to its decimal equivalent, which is 456.

Example 4: Invalid Hexadecimal String

<?php echo hexdec('G1'); ?>

Output:

Warning: hexdec(): Invalid hex string

Explanation: If the input string contains characters that are not valid in hexadecimal notation (like G), PHP will issue a warning and convert it as 0.

Example 5: Using Floating Point Numbers

<?php echo hexdec('1.2'); ?>

Output:

4.5

Explanation: The hexadecimal number 1.2 is converted to its decimal equivalent, which is 4.5.

Key Points:

  • Input Type: The input for hexdec() should be a string representing a valid hexadecimal number. If the string contains invalid characters, a warning will be issued.
  • Prefix: The 0x prefix is optional and can be included in the string to indicate that the number is in hexadecimal format.
  • Use Cases: This function is useful in various scenarios, including working with colors in web development (like CSS), data encoding, and low-level programming tasks.

Example of Practical Use:

<?php $hexColor = '#FF5733'; // Example color in hex // Extract the RGB components $red = hexdec(substr($hexColor, 1, 2)); // FF $green = hexdec(substr($hexColor, 3, 2)); // 57 $blue = hexdec(substr($hexColor, 5, 2)); // 33 echo "RGB representation of $hexColor is: ($red, $green, $blue)\n"; ?>

Output:

RGB representation of #FF5733 is: (255, 87, 51)

Explanation: This example demonstrates how to convert a hexadecimal color code into its RGB components using hexdec().

In summary, hexdec() is a helpful PHP function for converting hexadecimal numbers into decimal format, making it essential for applications involving hexadecimal notation, such as color representations, low-level data manipulation, and more.