从字面上将二进制数据写入文件 [英] Write binary data to file, literally

查看:115
本文介绍了从字面上将二进制数据写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数数组

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?

推荐答案

要将二进制数据写入文件,可以使用 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);

这篇关于从字面上将二进制数据写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆