我有一个文件,其中 32 位浮点值以标准的小端字节顺序存储,但交换了 32 位的高位字和低位字。
即当写入 IEEE-754 浮点数时读取为 0xDEADBEEF 的数字(值约为 6.26E18)按 0xBEEFDEAD 的顺序存储。
我想出了两种方法来做到这一点,但对我来说这两种方法似乎都不必要地复杂:
# Starting by reading the data as 16-bit words seems to be a good start:
words_in = np.fromfile("data.bin", dtype="uint16")
# Reverse word order, interpret as float and again reverse order of values:
words_backwards = words_in[-1::-1].copy()
float_values_backwards = words_backwards.view(">f4")
float_values = float_values_backwards[-1::-1]
# Above written in one line:
float_values = words_in[-1::-1].copy().view(">f4")[-1::-1]
# Or using reshaping and transpose operations (not sure if this avoits the object copy):
float_values = words_in.reshape(-1, 2).T[-1::-1].T.reshape(-1).view(">f4")
在 Python 中是否有更简单或更直观的方法来交换字序但保留字节顺序?
字节交换 16 位数组并查看为小端浮点数:
import numpy as np
data = bytes.fromhex('beefdead')
org = np.frombuffer(data, dtype=np.uint16)
fix = org.byteswap().view('<f4')
print(fix)
输出:
[-6.2598534e+18]