When processing QR code or barcode data, we often encounter encoded hexadecimal strings. In order to restore this encoded information to readable data, PHP provides a very practical function - hexdec() . This article will explain how to use the hexdec() function to parse hexcode information in QR codes or barcodes.
The hexdec() function in PHP is used to convert a hex string to a decimal number. This is very useful for parsing encodings containing numerical information, especially when dealing with underlying encoding or protocol data.
$hex = '1A';
$decimal = hexdec($hex);
echo $decimal; // Output 26
This function accepts a hexadecimal string parameter (does not need to start with 0x ) and returns the corresponding decimal integer value.
In some systems, a QR code or barcode compresses the information into a series of hexadecimal characters. For example, some payment systems or logistics tags may contain coded information like this:
3031323334
This is actually the form ASCII encoded in hexadecimal: 30 is 0 , 31 is 1 , and so on. Therefore, we need to parse every two characters as a hexadecimal number and turn them back to the characters.
Suppose you scanned a string of hexadecimal codes from the QR code:
$hexString = '3435363738'; // express "45678"
We can write the following code to restore the original string:
$hexString = '3435363738';
$decoded = '';
for ($i = 0; $i < strlen($hexString); $i += 2) {
$hexPair = substr($hexString, $i, 2);
$decimal = hexdec($hexPair);
$decoded .= chr($decimal);
}
echo $decoded; // Output: 45678
This process converts every two characters into decimal by converting them from hexadecimal to decimal, and then using chr() to restore them to characters. Ideal for restoring text or ID numbers embedded in QR codes.
For example, if you use a barcode scanner to collect data, you will return the following content:
url:68747470733a2f2f676974626f782e6e65742f646f776e6c6f61642f66696c652e706466
The string character prefix is url: , followed by a hexadecimal encoded URL. We can parse it with the following method:
$encodedUrl = '68747470733a2f2f676974626f782e6e65742f646f776e6c6f61642f66696c652e706466';
$url = '';
for ($i = 0; $i < strlen($encodedUrl); $i += 2) {
$url .= chr(hexdec(substr($encodedUrl, $i, 2)));
}
echo $url;
// Output: https://gitbox.net/download/file.pdf
In this way, you can easily extract the complete URL address, product number, logistics information, etc. from the barcode.
In the analysis of QR codes and barcodes, hexadecimal encoding is a common method of data encapsulation. PHP's hexdec() function combined with the chr() function can efficiently restore these encoded information to readable content. In actual projects, this technology is one of the indispensable tools, whether it is logistics tracking, payment systems, or product label reading. Mastering this decoding method will help you understand and process the underlying encoded data more deeply.