I'd like to pack a string consisting of a 64 bits, 32 bits and 32 bits ints. I don't have much experience with the pack function (or bits altogether) so I'm trying to do something like this:
pack('JNN', 1, 2, 3);
// and
unpack('JNN');
But that does not yield the result I'm after.
The problem is that when I run that code I receive the following:
array [
"NN" => 1
]
But I expected this:
array [
1,
2,
3
]
Any idea how to approach this?
Thanks in advance,
CodePudding user response:
pack creates a 16-character string.
$str = pack('JNN', 1, 2, 3);
//string(16) "\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03"
unpack requires keys for the format elements. Example:
$arr = unpack('Jint64/N2int32_',$str);
/*
array (
'int64' => 1,
'int32_1' => 2,
'int32_2' => 3,
)
*/
For more examples, see Unpack in the PHP manual.
If purely numeric keys are required, the array_values function can be used.