0

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.

harry
  • 1,410
  • 3
  • 12
  • 31

1 Answers1

2

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.

jspit
  • 7,276
  • 1
  • 9
  • 17
  • 1
    This. And if your hex number is a string, convert it to int first with `hexdec('0x1b12')`. – shevron Oct 07 '20 at 09:58
  • @jspit Many thanks for the answer. Would you be kind enough to tell me how this works actually? – harry Oct 07 '20 at 10:04
  • The function of the bit operators is described in detail in the PHP manual. I linked the section. – jspit Oct 07 '20 at 10:13
  • @jspit Thanks for linking the manual. But I just wanted to understand the logic used in here. – harry Oct 07 '20 at 10:44
  • The operation $val & 0xff filters the lowest 8 bits from the number. With $ val >> 8, the value of $val is shifted 8 bits to the right. 0x1b12 then becomes 0x1b. The repeated filtering is for safety. – jspit Oct 07 '20 at 10:57
  • @jspit However one problem that I ran into is, while converting a decimal value to a hexadecimal value using dechex this code doesn't seem to work correctly. It would be great if you could help me with this. Please see this pastebin. https://pastebin.com/5AetZRsz – harry Oct 09 '20 at 06:30
  • I added to my answer. I hope it's more understandable now. – jspit Oct 09 '20 at 16:21