使用numpy.fromfile读取二进制文件时字节序颠倒的解决方法
解决numpy读取二进制文件时的字节序颠倒问题
你遇到的是字节序不匹配的问题:文件中的二进制数据采用大端字节序(高位字节在前,比如A43C是A4(高位)先出现,3C(低位)后出现),而你的系统默认使用小端字节序,numpy读取时默认遵循系统字节序,所以导致解析出的数值字节颠倒。
下面是几种直接解决的方法:
方法一:读取时直接指定文件的字节序
在np.fromfile的dtype参数中,明确指定大端字节序的类型:
import numpy as np binary_stream = open('binary_file.bin', 'rb') numbers_to_read = 2 # >u2 表示大端字节序的无符号16位整数(2字节) numbers = np.fromfile(binary_stream, dtype='>u2', count=numbers_to_read, sep="") print(numbers[0]) # 输出:42044(对应十六进制A43C) print(numbers[1]) # 输出:47375(对应十六进制B90F)
这里的符号是字节序标记:
>代表大端(big-endian)<代表小端(little-endian)u2代表无符号16位整数(占用2字节)
方法二:读取后转换字节序
如果已经用默认的np.uint16读取了数据,可以通过byteswap()方法翻转每个元素的字节序:
import numpy as np binary_stream = open('binary_file.bin', 'rb') numbers_to_read = 2 numbers = np.fromfile(binary_stream, dtype=np.uint16, count=numbers_to_read, sep="") # 原地翻转字节序(inplace=True 避免创建新数组) numbers.byteswap(inplace=True) print(numbers[0]) # 输出:42044 print(numbers[1]) # 输出:47375
你也可以用newbyteorder()调整dtype的字节序,返回新数组:
numbers = numbers.astype(numbers.dtype.newbyteorder('>'))
内容的提问来源于stack exchange,提问作者jaj_develop
相关产品推荐
相关产品推荐

