PHP-将二进制打印到数组中

时间:2018-05-14 04:56:13

标签: php arrays binary

我已打印出这个二进制文件但尚未存储在数组中。

<?php
// get contents of a file into a string
$filename = "rock.wav";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));


for($i = 0; $i < strlen($contents); $i++) {
    $char = $contents[$i];

    $str = ord ($char);
	echo str_pad(decbin($str), 8,"0",STR_PAD_LEFT)."<br/>";

结果如下:

01010010
01001001
01000110
01000110
00000010

它更有可能万行。

我想将它们读入看起来像这样的数组,

[0] = '0';
[1] = '1';
[2] = '0';
[3] = '1';
[4] = '0';
[5] = '0';
[6] = '1';
[7] = '0';

[0] = '0';
[1] = '1';
[2] = '0';
[3] = '0';
[4] = '1';
[5] = '0';
[6] = '0';
[7] = '1';

如何做到这一点的任何线索?

2 个答案:

答案 0 :(得分:0)

$array = [];
for($i = 0; $i < strlen($contents); $i++) {
   $char = $contents[$i];

   $str = ord ($char);
   echo "<pre>";
   $array[] = str_split('',str_pad(decbin($str), 8,"0",STR_PAD_LEFT));
}
var_dump($array);

这应该有效

答案 1 :(得分:0)

您可以使用str_split

for($i = 0; $i < strlen($contents); $i++) {
    $char = $contents[$i];

    $str = ord ($char);
    $binArray = str_split(str_pad(decbin($str), 8,"0",STR_PAD_LEFT));
    print_r($binArray);    
}