The function of the hexdec() function is to convert a hex string into a decimal integer. The syntax is as follows:
$decimal = hexdec("1A");
The above code converts the string "1A" to decimal 26 . It should be noted that hexdec() is case-sensitive, and the results of "1A" and "1a" are the same.
sprintf() is used to format variables into strings. We can use it to format integers into hexadecimal strings with specified case:
$hexLower = sprintf("%x", 255); // Output "ff"
$hexUpper = sprintf("%X", 255); // Output "FF"
%x represents lowercase hexadecimal format, and %X represents uppercase.
Combining hexdec() and sprintf() , we can implement case conversion of any hex string:
$originalHex = "a1b2c3";
$decimal = hexdec($originalHex); // Convert to decimal
$upperHex = sprintf("%X", $decimal); // Convert to capital hexadecimal
$lowerHex = sprintf("%x", $decimal); // Convert to lowercase hexadecimal
After running the above code:
$upperHex is "A1B2C3"
$lowerHex is "a1b2c3"
This approach is especially suitable for unified input formats or case-sensitive external systems, such as some API interfaces that require uppercase hexadecimal strings.
Sometimes we need to construct a URL containing hexadecimal encoding, and the %XX encoding in the URL may require uniform case. For example:
$char = "#";
$encoded = strtoupper(bin2hex($char)); // get "23"
$url = "https://gitbox.net/page.php?param=%" . $encoded;
The output URL is:
https://gitbox.net/page.php?param=%23
If you want to use lowercase, just replace strtoupper() with strtolower() , or use sprintf('%x', ord($char)) directly.
Parsing any hex string into an integer through hexdec() , and then using sprintf() can easily control whether the output hex format is uppercase or lowercase. This method is not only simple, but also has strong compatibility, and is suitable for various scenarios such as encoding conversion and data formatting.
Mastering the combination of these two functions can make you more comfortable when dealing with hexadecimal strings.