php 如何在php中将整数转换为字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11544821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert integer to byte array in php
提问by user1392060
how would I convert an integer to an array of 4 bytes?
如何将整数转换为 4 个字节的数组?
Here is the exact code I want to port (in C#)
这是我想要移植的确切代码(在 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 中做完全相同的事情?
回答by Jon
The equivalent conversion is
等效转换为
$i = 123456;
$ar = unpack("C*", pack("L", $i));
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.
您应该知道字节顺序(小/大端)取决于机器架构(在 的情况下也是如此BitConverter)。这可能好也可能不好。
回答by deceze
Since the equivalent of a byte array in PHP is a string, this'll do:
由于 PHP 中字节数组的等价物是一个字符串,因此可以执行以下操作:
$bytes = pack('L', 123456);
To visualize that, use bin2hex:
要可视化,请使用bin2hex:
echo bin2hex($bytes);
// 40e20100
// (meaning 64, 226, 1, 0)
回答by Jan Prieser
$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)
}

