How to convert integer to byte array in php

2019-02-04 13:21发布

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 ?

标签: php bytearray
3条回答
Rolldiameter
2楼-- · 2019-02-04 13:38

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)
查看更多
Summer. ? 凉城
3楼-- · 2019-02-04 13:40
$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)
}
查看更多
你好瞎i
4楼-- · 2019-02-04 13:43

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.

查看更多
登录 后发表回答