我正在用 Python 编写一个二进制文件,以便用 C 读取。写入该文件的 (MWE) 代码是:
import struct
with open('test.bin', 'wb') as outfile:
outfile.write(struct.pack('didi', 1.2, 1, 1.3, 2))
当我用 C 读取文件时,我得到乱码数据:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main(int argc, char *argv[]) {
double testdouble, testdoubletwo;
int testint, testinttwo;
FILE *f = fopen("test.bin", "rb");
assert(f);
assert(fread(&testdouble, sizeof(testdouble), 1, f));
assert(fread(&testint, sizeof(testint), 1, f));
assert(fread(&testdoubletwo, sizeof(testdoubletwo), 1, f));
assert(fread(&testinttwo, sizeof(testinttwo), 1, f));
fprintf(stderr, "testdouble: %f, testint: %d, testdouble: %f, testinttwo: %d", testdouble, testint, testdoubletwo, testinttwo);
return 0;
}
输出:
testdouble: 1.200000, testint: 1, testdouble: -92559641157289301412905710012271939667257667601819249288413184.000000, testinttwo: 1073007820
如果我省略整数,它适用于这个小示例,但不适用于我正在读取几十个 double 的实际问题。其中一些(不是第一个,也不是最后一个)最终变成了乱码。
系统:Ubuntu 12.04,64位
python :2.7.3
最佳答案
在您的 C 代码中,您将每一项逐一读出,这意味着您没有应用任何对齐。试试这个:
outfile.write(struct.pack('=didi', 1.2, 1, 1.3, 2))
hexdump 测试.bin
0000000 3333 3333 3333 3ff3 0001 0000 cccd cccc
0000010 cccc 3ff4 0002 0000
C代码输出:
testdouble: 1.200000, testint: 1, testdouble: 1.300000, testinttwo: 2
如果不改python代码,还是用'滴滴',然后改c代码这样:
struct D {
double td;
int ti;
double td2;
int ti2;
};
struct D d;
fread(&d, sizeof(struct D), 1, f);
fprintf(stderr, "testdouble: %f, testint: %d, testdouble: %f, testinttwo: %d", d.td, d.ti, d.td2, d.ti2);
此测试在 Fedora 17 上,使用 python 2.7.3,gcc 4.7.2,我更喜欢定义结构。
关于python - 读取在 C 中使用 Python struct 编写的二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20334105/