What is the use of multiplying a set of bits by 256 when adding hexadecimal values?

Viewed 435

I am currently trying to decode a hexadecimal payload to extract values from it. The value to be converted is 0x7608. However, I am not getting the required result which should have been a 16 bit integer. The programming language being used is PHP.

$hex="7608";
$left_part="76";
$right_part="08";

$left_part_to_decimal= hexdec($left_part);
$right_part_to_decimal=hexdec($right_part);

$result=(left_part_to_decimal<<8)|($right_part_to_decimal);

The actual result is 30216. But i have been provided with a piece of code whereby the calculation of the result should have been as follows:

$result=($left_part_to_decimal & 0xFF) + ($right_part_to_decimal & 0xFF) * 256;

This leads to the expected result being 2166.

30216 is wrong and I can't seem to figure out why.

1 Answers

If you expect 2166 from 0x7608 the Bytes are swapped. "08" is the higher byte and "76" is the lower byte.

$hex="7608";
$bitStr = hex2bin($hex);  //same as "\x76\x08"

$integer = ord($bitStr[1]) * 256 +  ord($bitStr[0]); //2166

The unpack-function has both variants for 16 Bit. You can also do that:

$integer = unpack('v', $bitStr)[1];
Related