When porting C/C++ programs to PHP, you often encounter data format conversion problems. Especially in the case where hex strings are converted to integers, strtol is used to using this in C/C++, while in PHP, it is recommended to use the hexdec function to achieve similar effects.
This article will introduce the differences and usage of the two, and demonstrate with an example how to replace strtol with hexdec .
In C/C++, strtol is a powerful string to integer function. Its prototype is as follows:
long int strtol(const char *nptr, char **endptr, int base);
nptr : Points to the string to be converted.
endptr : Points to the part of the string that stops the conversion (can be NULL).
base : converts the binary (usually 10 or 16).
For example:
char *hex = "0x1A3F";
long result = strtol(hex, NULL, 16);
// result = 6719
PHP provides a built-in function hexdec to convert hex strings to decimal integers. The syntax is very simple:
int hexdec(string $hex_string);
Example of usage:
$hex = "1A3F";
$result = hexdec($hex);
// $result = 6719
Note that $hex should not contain the 0x prefix here, otherwise hexdec may not be parsed correctly.
When you replace strtol in C/C++ with hexdec in PHP, you need to pay attention to the following points:
Remove the prefix : PHP's hexdec does not accept 0x or 0X prefixes, and must be removed.
Input verification : strtol in C can identify the error part in the string, while hexdec does not have a similar parameter to return to the stop conversion position, and the string legality needs to be manually verified.
Case compatibility : PHP's hexdec automatically supports uppercase and lowercase letters A–F without conversion.
Here is a simple example showing how to convert a URL parameter containing a hexadecimal representation to an integer:
<?php
// Assumptions URL for https://gitbox.net/convert.php?hex=1A3F
$hex = $_GET['hex'] ?? '';
if (preg_match('/^[0-9a-fA-F]+$/', $hex)) {
$decimal = hexdec($hex);
echo "hexadecimal {$hex} 对应的十进制值for {$decimal}";
} else {
echo "无效的hexadecimal输入。";
}
?>
In this example, we first make sure the input is a legal hexadecimal number through a regular expression, and then call hexdec safely. It is consistent with the idea of using strtol(hex, NULL, 16) in C/C++, but it is more concise.
Although there is no multi-parameter function as flexible as strtol in PHP, hexdec is sufficient for most migration scenarios. As long as you pay attention to the input format and prefix processing, hexdec can well assume the role of strtol in C/C++ and complete the safe conversion from hex to decimal. For scenarios where more complex processing is required, combining regular verification or manual processing of strings is also a completely feasible strategy.