php解码或解析十六进制的每个半字节

时间:2014-10-28 19:22:21

标签: php hex decode php4 php-5.5

我们如何在php中解码十六进制值?

我有十六进制值来编码一些数据。

对于ex:我的十六进制值= 0x 1121 0031 在这里,这个十六进制值的每个半字节告诉我类似于第一个半字节1表示product_1和2表示product_2。对于第二个半字节1意味着新产品,2意味着旧产品。

如何解析每个半字节?

1 个答案:

答案 0 :(得分:0)

您可以直接从字符串中提取每个半字节并将其比较如下:

$data = '0x 1121 0031';
$data = substr($data, 2); //remove the 0x prefix from the string
$data = str_replace(' ', '', $data); //remove the spaces from the string
//$data is now '11210031'
echo 'the product number is ' . $data[0] . "\n";
if ($data[1] == 1) {
    echo "this is a new product\n";
} else if ($data[1] == 2) {
    echo "this is a used product\n";
}

您还可以将字符串解释为数字,然后提取位:

$data = '0x 1121 0031';
$data = substr($data, 2); //remove the 0x prefix from the string
$data = str_replace(' ', '', $data); //remove the spaces from the string
//$data is now '11210031'
$number = hexdec($data); //convert the hexadecimal number to an integer
//$number is now 0x11210031 (hexadecimal) = 287375409 (decimal)
$nibble1 = ($number >> 28) & 0xF; //shift the number right by 28 bits (each nibble is 4 bits) and select only the last 4 bits (0xF selects all bits in the last nibble)
echo "the product number is $nibble1\n";
$nibble2 = ($number >> 24) & 0xF;
if ($nibble2 == 1) {
    echo "this is a new product\n";
} else if ($nibble2 == 2) {
    echo "this is a used product\n";
}