How to convert integer to byte array in php

2019-02-04 13:05发布

问题:

how would I convert an integer to an array of 4 bytes?

Here is the exact code I want to port (in C#)

int i = 123456;
byte[] ar = BitConverter.GetBytes(i);
// ar will contain {64, 226, 1, 0}

How would I do the exact same thing in PHP ?

回答1:

The equivalent conversion is

$i = 123456;
$ar = unpack("C*", pack("L", $i));

See it in action.

You should be aware though that the byte order (little/big endian) is dependent on the machine architecture (as it is also in the case of BitConverter). That might or might not be good.



回答2:

Since the equivalent of a byte array in PHP is a string, this'll do:

$bytes = pack('L', 123456);

To visualize that, use bin2hex:

echo bin2hex($bytes);
// 40e20100
// (meaning 64, 226, 1, 0)


回答3:

$i = 123456;
$byte_array = unpack('C*', $i);

var_dump($byte_array);
array(6) {
  [1]=>
  int(49)
  [2]=>
  int(50)
  [3]=>
  int(51)
  [4]=>
  int(52)
  [5]=>
  int(53)
  [6]=>
  int(54)
}


标签: php bytearray