PHP 读取文件作为字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17963110/
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
PHP read file as an array of bytes
提问by BlackRoot
I have a file written using JAVA
program which has an array of integers written as binary I made an for loop over this array and write it using this method
我有一个使用JAVA
程序编写的文件,它有一个整数数组写成二进制我在这个数组上做了一个 for 循环并使用这个方法编写它
public static void writeInt(OutputStream out, int v) throws IOException {
out.write((v >>> 24) & 0xFF);
out.write((v >>> 16) & 0xFF);
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
}
I'm ask about how to read this file in PHP
.
我问的是如何在PHP
.
回答by Orangepill
I believe the code you are looking for is:
我相信您正在寻找的代码是:
$byteArray = unpack("N*",file_get_contents($filename));
UPDATE:Working code supplied by OP
更新:OP 提供的工作代码
$filename = "myFile.sav";
$handle = fopen($filename, "rb");
$fsize = filesize($filename);
$contents = fread($handle, $fsize);
$byteArray = unpack("N*",$contents);
print_r($byteArray);
for($n = 0; $n < 16; $n++)
{
echo $byteArray [$n].'<br/>';
}
回答by Joni
You should read the file as a string and then use unpack to parse it. In this case you have stored a 32-bit integer in big endian byte order, so use:
您应该将文件作为字符串读取,然后使用 unpack 来解析它。在这种情况下,您以大端字节顺序存储了一个 32 位整数,因此请使用:
$out = unpack("N", $in);
The format codes are documented here: http://www.php.net/manual/en/function.pack.php
格式代码记录在此处:http: //www.php.net/manual/en/function.pack.php