python - 读取在 C 中使用 Python struct 编写的二进制数据

标签 python c io

我正在用 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/

相关文章:

python - 如何获取歌曲中歌词的时间戳?

python - 使用 numpy dtype 和转换器将 csv 列拆分为子列

c - 为什么指向字符串的指针存储在 .rodata 中,而指向 int 的指针却在堆栈上?

java - 为什么使用PrintWriter时数据无法写入文件?

python - 在 plt.contourf 中使用非线性级别时保持颜色图的线性颜色

python - 使用 df.to_csv 时如何保留字符串数据

c - 为什么输出是这样呢?

c++ - OpenGL Nvidia 驱动程序 259.12 纹理不工作

io - 在非 DMA 场景中,在磁盘读取期间,存储设备/磁盘内容是否先进入 CPU 寄存器,然后再进入主内存?

java - 从二进制文件中读取特定字节