質問

in php 4.4.4 having:

$hbc=pack("LL",82603088,82602992);
list($v1,$v2)=unpack("L2",$hbc);
echo("v1=".$v1." v2=".$v2);

result is:

v1= v2=82603088

I already have some hours wrapping my head aroud this... thanks

役に立ちましたか?

解決

The error is not withing the pack or unpack, but inside the list().

Turn on notices! Your code will complain like this:

Notice: Undefined offset: 0 in ...

That should make you wonder. If you dump the array that is returned by unpack, it is correct:

array(2) {
  [1] =>
  int(82603088)
  [2] =>
  int(82602992)
}

And then there is this tiny little note on the docs page of list():

list() only works on numerical arrays and assumes the numerical indices start at 0.

Your array does not start at index 0, and the notice likes to tell you that.

The quick fix is:

list(,$v1,$v2)=unpack("L2",$hbc); // add a comma to skip index 0

A better approach might be to use unpack to create named array indices:

$unpacked = unpack("L2v/",$hbc);

Result:

array(2) {
  'v1' =>
  int(82603088)
  'v2' =>
  int(82602992)
}

他のヒント

From the php.net comments.

$int_list = array_merge(unpack("s*", $some_binary_data));

This will essentially reset your index keys starting at 0.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top