Unpack hex-encoded binary data in PHP

We’re collecting data from a partner’s IoT devices and the data comes encoded in a hex string like 1C000000010028 which contains binary data:

  • Byte 0 bit 0 Boolean
  • Byte 0 bit 1 Boolean
  • Byte 0 bit 2 Boolean
  • Byte 0 bit 3 Boolean
  • Byte 0 bits 4-7 UInt4
  • Bytes 1-2 bits 0-15 UInt16
  • Byte 3 bits 0-7 UInt8
  • Bytes 4-5 bits 0-15 UInt16
  • Byte 6 bits 0-7 UInt8

I have never worked with this kind of data and am wondering how to decode / unpack this in PHP. I was guessing that https://www.php.net/manual/de/function.unpack.php would be my friend but I just don’t get it. Any help would be much appreciated, thanks!

Answer

They say that the input is a hex string like ‘1C000000010028’.

$code = '1C000000010028';

To use unpack() the data must be a string with binaryData. You can convert it with hex2bin.

$binaryData = hex2bin($code);
// "x1cx00x00x00x01x00x28"

Now you could use unpack.

$arr = unpack('Cbyte_0/vUInt16_0/Cbyte_1/vUInt16_1/Cbyte_2',$binaryData);
/*
$arr = array (
  'byte_0' => 28,
  'UInt16_0' => 0,
  'byte_1' => 0,
  'UInt16_1' => 1,
  'byte_2' => 40,
)
*/

Individual data types such as Boolean and UInt4 are not included in the pack/unpack formats. To get this data you have to work with the bit operators.

Just one example of this:

$byte_0bit2 = (bool)($arr['byte_0'] & 0b00000100);

This can lead to further questions, the answers of which can be found here on Stackoverflow.

Leave a Reply

Your email address will not be published. Required fields are marked *