.bin文件的Python Big-Endian转换

问题描述

我正在尝试将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')

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...