Stefatronik
Stefatronik

Reputation: 332

PHP pack: do not really understand

I posted this (php pack: problems with data types and verification of my results) and found that I had two problems. So here again only one issue (I solved the other one) Hopefully this is easy to understand: I want to use the PHP pack() function. 1) My aim is to convert any integer number info a hex one of length 2-Bytes. Example: 0d37 --> 0x0025

2) Second aim is to toggle high / low byte of each value: 0x0025 --> 0x2500 3) There are many input values which will form 12-Bytes of binary data.

Can anyone help me?

Upvotes: 2

Views: 1074

Answers (1)

Narf
Narf

Reputation: 14762

You just have to lookup the format table in the pack() manual page and it is quite easy.

2 bytes means 16 bits, or also called a "short". I assume you want that unsigned ... so we get n for big endian (high) and v for little endian (low) byte order.

The only potentially tricky part is figuring out how to combine the format and parameters, as each format character is tied to a value argument:

bin2hex(pack('nv', 34, 34)) // returns 00222200

If you need a variable number of values, you'll need agument unpacking (a PHP language feature, not to be confused with unpack()):

$format = 'nv';
$values = [34, 34];
pack($format, ... $values); // does the same thing

And alternatively, if all of your values should be packed with the same format, you could do this:

pack('v*', $values); // will "pack" as many short integers as you want

Upvotes: 3

Related Questions