Current Location: Home> Latest Articles> Use hexdec to parse hex timestamps or IDs

Use hexdec to parse hex timestamps or IDs

gitbox 2025-05-28

What is hexdec()

hexdec() is one of the built-in functions in PHP, which is used to convert a hexadecimal string (composed of letters and numbers, 0-9, af) into a decimal integer. This is especially useful for handling data in certain external systems, logging or databases, especially when such data is passed or stored in hexadecimal form.

Function signature:

 int hexdec(string $hex_string)

Example of parsing hexadecimal timestamps

Suppose we receive a timestamp in hexadecimal format, for example:

 $hexTimestamp = '5f4dcc3b';

We want to convert it into human-readable dates and times.

 <?php

$hexTimestamp = '5f4dcc3b';
$decimalTimestamp = hexdec($hexTimestamp);

echo "Hexadecimal timestamp:$hexTimestamp\n";
echo "Decimal timestamp:$decimalTimestamp\n";
echo "Readable time:".date('Y-m-d H:i:s', $decimalTimestamp)."\n";

?>

The output may be similar:

 Hexadecimal timestamp:5f4dcc3b
Decimal timestamp:1598887867
Readable time:2020-08-31 16:51:07

Use hexadecimal ID in URL parameters

IDs in hexadecimal format are often used to generate links, such as unique identifiers for a resource:

 <?php

$hexId = '1a2b3c4d';
$decimalId = hexdec($hexId);

$url = "https://gitbox.net/resource.php?id=$decimalId";

echo "Original hexadecimalID:$hexId\n";
echo "ConvertedURL:$url\n";

?>

The generated link will have a decimal ID that is easier to identify and process:

 Original hexadecimalID:1a2b3c4d
ConvertedURL:https://gitbox.net/resource.php?id=439041101

This transformation is very practical when handling short links, API parameters, log analysis, or database queries.

Error handling prompts

Although hexdec() is a very direct function, you should pay attention to the legality of the input value when using it. For example, non-hexadecimal characters will be ignored, which may lead to unexpected results:

 <?php

$badHex = 'zz123'; // Illegal characters
echo hexdec($badHex); // The output is0,Because there are no legal characters at the beginning

?>

It is recommended to verify the input value before formal use or use regularity to determine its legality.