How to find the Lower and Upper Byte from Hex value in PHP?

612 views Asked by At

I have a series of Hex values like 0x1b12, 0x241B, 0x2E24, 0x392E and I need to calculate the Lower byte and Upper Byte from each of these hex values for further processing. How can I do that? I did a bit of research and saw that there is an unpack function in php but the "format" part in the argument is making me confused. Some of the unpack code that I've seen is added below.

unpack("C*",$data)
unpack("C*myint",$data)
unpack("c2chars/n2int",$data)

As mentioned the aforementioned code, I don't quite understand what "C*","C*myint","c2chars/n2int" does in the unpack function. So I'm not quite sure if I can use unpack as the solution to my problem. Your help is much appreciated.

Thanks in advance.

1

There are 1 answers

7
jspit On BEST ANSWER

You can do this with the pack function. It is easier and faster with Bitwise Operators:

$val = 0x1b12;  //or $val = 6930;

$lowByte = $val & 0xff;  //int(18)
$uppByte = ($val >> 8) & 0xff;  //int(27)

The code needs an integer $val as input. If a string of the form "0x1b12" is available as input, then this must be converted into an integer:

$stringHex = "0x1b12";  //or "1b12"
$val = hexdec(ltrim($stringHex,'0x'));

ltrim is required so that no depreciation notice is generated from 7.4.0 onwards.