怎么从文件中读取结构化的二进制数据?
本教程将介绍如何从文件中读取结构化的二进制数据?的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。
问题描述
以下C++代码将头文件写入文件:
#include <iostream>
struct Header
{
uint16_t name;
uint8_t type;
uint8_t padding;
uint32_t width, height;
uint32_t depth1, depth2;
float dMin, dMax;
};
int main()
{
Header header;
header.name = *reinterpret_cast<const uint16_t*>("XO");
header.type = true;
header.width = (uint32_t)512;
header.height = (uint32_t)600;
header.depth1 = (uint32_t)16;
header.depth2 = (uint32_t)25;
header.dMin = 5.0;
header.dMax = 8.6;
FILE* f = fopen("header.bin", "wb");
fwrite(&header, sizeof(Header), 1, f);
}
我希望使用Python读取这些header.bin
文件。在C++中,我将执行如下操作:
fread(&header, sizeof(Header), 1, f)
但我不确定怎么读取字节并将它们转换为头结构在Python中具有的相应字段?
推荐答案
使用struct
module定义类C结构的二进制布局并将其反/序列化:
import struct
# Format String describing the data layout
layout = "H B x 2L 2L 2f"
# Object representing the layout, including size
header = struct.Struct(layout)
with open("header.bin", "rb") as in_stream:
print(header.unpack(in_stream.read(header.size))
layout
是按顺序描述字段的format string,例如H
表示uint16_t
,B
表示uint8_t
,x
表示填充字节,依此类推。
好了关于怎么从文件中读取结构化的二进制数据?的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。