How to convert integer to byte array in php

安稳与你 提交于 2020-01-09 19:29:11

问题


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)
}


来源:https://stackoverflow.com/questions/11544821/how-to-convert-integer-to-byte-array-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!