从 c++ 到 python 的二进制读取器

Binary reader from c++ to python

本文关键字:二进制 读取 python c++      更新时间:2023-10-16

我有一个 c++ 的二进制阅读器,我正在尝试用 python 编写同样的东西(两种语言的初学者(。我在网上阅读,我看到我应该使用结构,但我在完成它时遇到了麻烦。 我的 c++ 代码如下:

struct databin {
float prixc[60];
float volume[60];
};
databin qt;
//get the data for day d, minute i//
int numsteps = m_nbsteps * sizeof(qt);
int step = d*numsteps+i*sizeof(qt);
m_rf.seekg(step, ios::beg); 
m_rf.read((char*) &qt, sizeof(qt));
// at the end we have the data in the object qt

我真的很感激在 python 中做同样的事情的一些帮助。 谢谢!!

更新: 对不起,马克,我不希望我的信息被这样认为。真的很感激你花的时间。

实际上,我更像是在寻找"struct"的起点,因为我在 c 中的结构由两个数组组成,我找不到如何在 python 中使用相同类型的结构才能使用 unpack。

到目前为止,我做了什么:


//get the data for day d, minute i//
d=5000
i=15    
numsteps=391*480
x=[]
y=[]
step=d*numsteps+i*480
with open(file, "rb") as of: 
of.seek(step, 0) 
couple_bytes = of.read(480)
for j in range(0,240,4):
[x] = struct.unpack('f', couple_bytes[j:j+4])
xx.append(x)
for j in range(244,480,4):
[y] = struct.unpack('f', couple_bytes[j:j+4])   
yy.append(y)

现在这有效,在 xx 和 yy 中,我有我的 2 个数组。但我的目标是通过定义结构并直接阅读它来获得更直接的方法。

再次感谢!

struct模块能够通过在格式字符串中包含计数来一次解压缩多个值。

with open(file, "rb") as of: 
of.seek(step, 0) 
couple_bytes = of.read(60*4)
prixc = list(struct.unpack('60f', couple_bytes))
couple_bytes = of.read(60*4)
volume = list(struct.unpack('60f', couple_bytes))