PHP:从二进制数据流中解压缩32位整数

时间:2017-12-28 16:03:46

标签: php binary

我有一个1024位长的二进制数据流,我想将其转换为32位整数数组(e.i。32个数字)。 从question开始,我使用了这段代码:

$filename = "myFile.sav"; 
$handle = fopen($filename, "rb"); 
$fsize = filesize($filename); 
$contents = fread($handle, $fsize); 
$byteArray = unpack("N*",$contents); 
print_r($byteArray); 

即使它将自身格式化为" N",var_dump然后打印出256个8位长整数的数组。 (我想要32个32位长数字)。我究竟做错了什么?

编辑:它实际上不是256个8位数字,而是256个乱码值

1 个答案:

答案 0 :(得分:1)

您的文件似乎包含整数的二进制表示形式。给定任何string位表示,bindec函数会将它们正确转换为integer

$content = "1000110010110110100100101011000100100000101011010101101110101101011101110011001110010010111101001011111000111000101110011110011100110110000111001110000011001101011100111011110000001110111100100110110001000111111001010101100011100101010111000011010101010010001101101100011001101110001001000101110111011001001101111000110101010001101010000101110000100010000110110111000110001110000010000111001100100111110011000101000110100011111100100011110100101010101101011011101100111000101011110111111010001110000011101001011101111010101010011010011010011101100011111111000110000110000000000101110110010100010011010001110101101100110110001011010010010000011000111101110000100100001101100010101011000110010110110111100111010010101110000101011101010010101110100111100111110011000100001010111110010001010100001010001011101101110010011001010000101011110101100001100001111011101010100001001101100100110001101000000110111000111001100001000110000011011100000100011100100110101101000101111011110001100110010001111111010101110111111010110010111001";

$parts = str_split($content, 32);

for ($i = 0; $i < count($parts); ++$i) {
    $parts[$i] = bindec($parts[$i]);
}

print_r($parts);