John Davidson

bit - PHP pack with multiple values with different lengths

0 comments
Message:


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,



My Answer:
1, 0, 0]_// instead of [1, 2, 3]__The issue here is that the 'J' format specifier in the pack function is for a 64-bit unsigned integer, which is larger than the 32-bit integers you are trying to pack. To pack a 32-bit integer, you should use the 'N' format specifier instead._So the correct way to pack and unpack the values would be:_php$packed = pack('NNN', 1, 2, 3);$unpacked = unpack('N1a/N1b/N1c', $packed);print_r($unpacked);_This will output:_Array[ [a] => 1 [b] => 2 [c] => 3]

Rate this post

3 of 5 based on 2970 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us