【问题标题】:How to make a binary file? [closed]如何制作二进制文件? [关闭]
【发布时间】:2014-05-17 06:45:31
【问题描述】:

我想用 PHP 制作一个二进制文件,我想用那个二进制文件来存储一系列整数,例如

66 23 44 55 80 258 

以二进制形式来节省一些内存空间,因为它应该比文本文件小得多。我要问的是如何使用 PHP 编写二进制文件?我知道您可以使用 file_put_contents() 创建一个文本文件,但如何编写二进制文件?

【问题讨论】:

标签: php binaryfiles


【解决方案1】:

这里有一个解决方案:

$fHandle=fopen("sampleFile","wb");//opens for writing

//pack (signed) short ints(16 bit) in binary string (see documentation for more options)
//signed short should do for int's in range –32768 to 32767 and unsigned - 0 to 65,535
$byteArray = pack("s*", 32, 12, 14, 18, 1066);

fwrite($fHandle, $byteArray);//write data to the file
fclose($fHandle);

当您阅读文件时:

$fHandle=fopen("sampleFile", "rb");
$bArray=fread($fHandle, filesize("sampleFile"));
$intArray=unpack("s*", $ba2);//unpack it with the same mode as you pack()'d it

echo $intArray[0];//should give 32
echo $intArray[1];//should give 12
echo $intArray[4];//should give 1066

编辑:更改了一些字符串以纠正标点错误

【讨论】:

    猜你喜欢
    • 2014-10-25
    • 2017-06-13
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2016-08-31
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多