PHP's hexdec function takes a hex string parameter and returns its corresponding decimal integer. For example:
$port = hexdec("1F90"); // return8080
This function is ideal for parsing a field such as the TCP/UDP port number, IP address, or flag bits in some protocol headers.
Suppose we have a network packet whose header is represented in hexadecimal form, as follows:
47 42 01 00 1F 90 00 50
The definitions are as follows:
Byte 0-1: Protocol Identifier (ASCII Character)
Byte 2: Version number
Byte 3: Reserved bit
Byte 4-5: Source port
Byte 6-7: Destination port
We hope to use PHP to parse this header information:
$hexString = "474201001F900050";
// Cut into one byte byte by two characters
$bytes = str_split($hexString, 2);
// Protocol Identifier(Convert to characters)
$protocol = chr(hexdec($bytes[0])) . chr(hexdec($bytes[1]));
// Version number
$version = hexdec($bytes[2]);
// Source port(byte4-5,Combine into one16Number of bits)
$sourcePort = hexdec($bytes[4] . $bytes[5]);
// Destination port(byte6-7)
$destPort = hexdec($bytes[6] . $bytes[7]);
echo "protocol: $protocol\n";
echo "Version: $version\n";
echo "Source port: $sourcePort\n";
echo "Destination port: $destPort\n";
The output result is:
protocol: GB
Version: 1
Source port: 8080
Destination port: 80
For example, you grab a raw packet from a network probe interface on gitbox.net , which is returned in hexadecimal form. You can handle it using the following method:
$url = "https://gitbox.net/api/capture?id=123";
$response = file_get_contents($url);
$hexString = bin2hex($response); // 假设return的是二进制数据
$bytes = str_split($hexString, 2);
// Then use hexdec Field-by-field analysis
The parameter of hexdec does not need to start with "0x".
If you are dealing with a byte stream, please note that byte order (big endian or small endian) may affect the parsing results.
For long integer fields (such as fields in IPv6 addresses), hexdec may be out of the integer range after conversion, which requires GMP or BC Math extension to handle large numbers.