Python .bin 文件的大端转换

Python Big-Endian Conversion for .bin file

我正在尝试将二进制文件的 Matlab 代码转换为 Python。请原谅我是这门语言的新手。

Matlab:

fileID = fopen('file_name.bin','r');
DC = fread(fileID,'single','b');

Python:

import numpy as np
with open('Duty_Cycle.bin','rb') as fid:
    data_array = np.fromfile(fid, np.float32, dtype = '>u4')
print(data_array)

结果:

TypeError: argument for fromfile() given by name ('dtype') and position (2)

我该如何解决这个错误?

fromfile 的签名是

fromfile(file, dtype=float, count=-1, sep='', offset=0)

通过指定第二个位置参数 np.float32 和关键字参数 dtype='>u4',您给出了相同的参数两次,因此出现了错误。文档不是很清楚,但您可以使用字符串规范来指定类型和字节顺序。

data_array = np.fromfile(fid, dtype='>u4')