You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:01:07