简体   繁体   English

Matlab-> Python,如何将二进制文件转换为一维浮点数组? 在Matlab中工作正常,但无法在Python中重现

[英]Matlab -> Python, how do I convert binary file to 1d float array? Works fine in Matlab but unable to reproduce in Python

In Matlab, binary file section 'block' is 2048 bytes and is read as follows: 在Matlab中,二进制文件节“块”为2048字节,其读取方式如下:

fseek(fileID, 2024, 'bof');
data = fread(fileID, block, '*float');

Output of data is a 2048x1 single precision array, example below... 数据输出是一个2048x1单精度数组,下面的示例...

15.5567
-1.9876
0.0529
25.97620

In Python, I make sure to seek to same section of the file and use 2048 bytes 'block' to read the binary section. 在Python中,请确保查找文件的同一部分,并使用2048字节的“块”读取二进制部分。 I then tried to use struct unpack function to convert the binary to the single precision floating numbers. 然后,我尝试使用struct unpack函数将二进制转换为单精度浮点数。

fileID.seek(2024,0)
data = unpack('2048f',block)

First, I get errors for bytes object of length. 首先,我得到长度对象字节的错误。 So I change size to see if atleast the output will give me something similar. 所以我更改大小以查看输出是否至少会给我类似的东西。

data = unpack('512f',block)
print(data)

Output gives very small and larger numbers 输出给出非常小的数字

-14.858826637268066
5.938749347655264e-36
1.767982006072998
-24509016064.0

Any help is appreciated. 任何帮助表示赞赏。 I also tried to use 我也尝试使用

data = numpy.frombuffer(block, dtype=numpy.float32)

with basically same results. 结果基本相同。

Here is the answer I found. 这是我找到的答案。 Works perfectly. 完美运作。

 data = []

 for i in range(0, 2048): 
    data.append(unpack('>f', fileID.read(4))[0]

The output of data is exactly the same as Matlab. 数据输出与Matlab完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM