0
我們如何解碼php中的十六進制值?php解碼或解析每個十六進制的半字節
我有十六進制值,它編碼了一些數據。
對於例如:我的十六進制值= 0x 1121 0031 這裏,這個十六進制值的每個半字節告訴我像第一個半字節1表示product_1和product_2的東西。而第二個半字節1表示新產品,2表示舊產品。
我該如何解析每個半字節?
我們如何解碼php中的十六進制值?php解碼或解析每個十六進制的半字節
我有十六進制值,它編碼了一些數據。
對於例如:我的十六進制值= 0x 1121 0031 這裏,這個十六進制值的每個半字節告訴我像第一個半字節1表示product_1和product_2的東西。而第二個半字節1表示新產品,2表示舊產品。
我該如何解析每個半字節?
您可以提取直接從字符串中的每個蠶食它這樣比較:
$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";
}