从字面上将二进制数据写入文件

编程入门 行业动态 更新时间:2024-10-28 19:32:39
本文介绍了从字面上将二进制数据写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个整数数组

Array ( [0] => Array ( [0] => 1531412763 [1] => 1439959339 [2] => 76 [3] => 122 [4] => 200 [5] => 4550 [6] => 444 ) ...

以此类推,我想,如果我将它看作是一个数据库,则是最外层数组的元素是行,而内层数组的元素是列.

And so on, I suppose if I look at it as if it were a database - the elements of the outermost array are the rows and the elements of the inner arrays are the columns.

我想将该信息保存到文件中,以便以后可以检索,但我想将其另存为二进制数据以节省空间.基本上,如果我将示例1531412763中的第一个整数写入文件,它将占用10个字节,但是如果我将其另存为有符号整数,则它将占用4个字节.

I want to save that information into a file, so that I will be able to retrieve it later but I want to save it as binary data to save space. Basically if I write the first integer from the example 1531412763 to a file it will take up 10 bytes but if I could save it as a signed integer it would take up 4 bytes.

我查看了许多其他答案,这些答案都建议使用fwrite,但我不明白如何以这种方式使用?

I have looked at a number of other answers which all suggest using fwrite which I can't understand how to use in such manner?

推荐答案

要将二进制数据写入文件,可以使用 pack() 和 unpack() . Pack将产生一个二进制字符串.结果是一个字符串,您可以将整数连接成一个字符串.然后将此字符串作为一行写到您的文件中.

For writing binary data to a file, you can use the functions pack() and unpack(). Pack will produce a binary string. As the result is a string, you can concatenate the ints into a single string. Then write this string as a line to your file.

通过这种方式,您可以轻松地使用file()进行阅读,这会将文件放入一行行中.然后只需unpack()每行,就可以恢复原始数组.

This way you can easily read with file() which will put the file into an array of lines. Then just unpack() each line, and you have your original array back.

类似这样的东西:

$arr = array( array ( 1531412763, 1439959339 ), array ( 123, 456, 789 ), ); $file_w = fopen('binint', 'w+'); // Creating file content : concatenation of binary strings $bin_str = ''; foreach ($arr as $inner_array_of_int) { foreach ($inner_array_of_int as $num) { // Use of i format (integer). If you want to change format // according to the value of $num, you will have to save the // format too. $bin_str .= pack('i', $num); } $bin_str .= "\n"; } fwrite($file_w, $bin_str); fclose($file_w); // Now read and test. $lines_read will contain an array like the original. $lines_read = []; // We use file function to read the file as an array of lines. $file_r = file('binint'); // Unpack all lines foreach ($file_r as $line) { // Format is i* because we may have more than 1 int in the line // If you changed format while packing, you will have to unpack with the // corresponding same format $lines_read[] = unpack('i*', $line); } var_dump($lines_read);

更多推荐

从字面上将二进制数据写入文件

本文发布于:2023-11-23 11:02:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621215.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字面   上将   文件   二进制数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!