Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP hexdec() Function
The hexdec() function converts a hexadecimal string to its decimal equivalent. This function is useful when working with color codes, memory addresses, or any data represented in hexadecimal format.
Syntax
hexdec(string $hex_string): int|float
Parameters
| Parameter | Description |
|---|---|
| hex_string | The hexadecimal string to convert. Can include optional 0x prefix |
Return Value
Returns the decimal representation as an integer or float. Large values may return as float due to integer overflow.
Examples
Basic Hexadecimal Conversion
Converting common hexadecimal values to decimal ?
<?php
echo "hexdec('A') = " . hexdec('A') . "<br>";
echo "hexdec('FF') = " . hexdec('FF') . "<br>";
echo "hexdec('1A') = " . hexdec('1A') . "<br>";
echo "hexdec('0x1A') = " . hexdec('0x1A') . "<br>";
?>
hexdec('A') = 10
hexdec('FF') = 255
hexdec('1A') = 26
hexdec('0x1A') = 26
Color Code Conversion
Converting HTML color codes to decimal values ?
<?php
$color = 'FF5733';
$red = hexdec(substr($color, 0, 2));
$green = hexdec(substr($color, 2, 2));
$blue = hexdec(substr($color, 4, 2));
echo "Color #$color:<br>";
echo "Red: $red<br>";
echo "Green: $green<br>";
echo "Blue: $blue<br>";
?>
Color #FF5733: Red: 255 Green: 87 Blue: 51
Large Values and Edge Cases
Demonstrating behavior with large numbers and invalid input ?
<?php
echo "hexdec('FFFFFFFF') = " . hexdec('FFFFFFFF') . "<br>";
echo "hexdec('G') = " . hexdec('G') . "<br>";
echo "hexdec('') = " . hexdec('') . "<br>";
?>
hexdec('FFFFFFFF') = 4294967295
hexdec('G') = 0
hexdec('') = 0
Key Points
? Case insensitive − 'ff' and 'FF' produce the same result
? Invalid characters are ignored and conversion stops at first invalid character
? Empty strings or strings with no valid hex characters return 0
? Optional '0x' prefix is supported
Conclusion
The hexdec() function provides a simple way to convert hexadecimal strings to decimal numbers. It's particularly useful for color manipulation, binary data processing, and working with memory addresses in PHP applications.
