Skip to content

NumPy - 字节交换

计算机内存使用特定的字节顺序(称为 字节序)存储多字节数据类型(如整数或浮点数)。它指的是字节在内存中的排列顺序。

  • 小端序: 最低有效字节 (LSB) 存储在最小内存地址。
  • 大端序: 最高有效字节 (MSB) 存储在最小内存地址。

大多数现代处理器(如 Intel x86/x64)是小端序,而其他一些处理器(一些较旧的架构、网络字节序)是大端序。当在不同字节序的系统之间共享二进制数据,或从具有特定字节顺序的文件中读取数据时,您可能需要交换字节顺序。

NumPy 提供了 ndarray.byteswap() 方法,用于在小端序和大端序表示之间切换数组数据的字节顺序。

ndarray.byteswap(inplace=False)

参数:

  • inplace: 如果设置为 True,则直接在数组数据上执行字节交换(原地操作)。如果设置为 False(默认值),则返回一个字节顺序已交换的 新 数组,原数组保持不变。

让我们用一个使用 16 位整数(np.int16,占用 2 个字节)的例子来说明:

import numpy as np
# Create an array of 16-bit integers
# 1 = 0x0001, 256 = 0x0100, 8755 = 0x2233
a = np.array([1, 256, 8755], dtype=np.int16)
print(f"Original array: {a}")
# Display hexadecimal representation (assuming little-endian machine)
# On little-endian: 1 -> 01 00, 256 -> 00 01, 8755 -> 33 22
print(f"Hex representation (native): {[hex(x) for x in a]}")
print(f"Raw bytes (native endian): {a.tobytes().hex(' ')}")
# Swap bytes IN-PLACE
print("\nApplying byteswap(inplace=True)...")
a.byteswap(inplace=True)
print(f"Array after in-place byteswap: {a}")
# Swapped values: 0x0100 = 256, 0x0001 = 1, 0x3322 = 13090
print(f"Hex representation (swapped): {[hex(x) for x in a]}")
print(f"Raw bytes (swapped endian): {a.tobytes().hex(' ')}")
# Swap bytes and return a NEW array (original 'a' remains swapped)
print("\nApplying byteswap(inplace=False) on the already swapped array...")
b = a.byteswap(inplace=False) # Swaps back to original byte order
print(f"Original array 'a' (still swapped): {a}")
print(f"New array 'b' (swapped back): {b}")
print(f"Raw bytes of 'b': {b.tobytes().hex(' ')}")

预期输出(确切的十六进制值取决于系统字节序,这里假设是小端序):

Original array: [ 1 256 8755]
Hex representation (native): ['0x1', '0x100', '0x2233']
Raw bytes (native endian): 01 00 00 01 33 22
Applying byteswap(inplace=True)...
Array after in-place byteswap: [ 256 1 13090]
Hex representation (swapped): ['0x100', '0x1', '0x3322']
Raw bytes (swapped endian): 00 01 01 00 22 33
Applying byteswap(inplace=False) on the already swapped array...
Original array 'a' (still swapped): [ 256 1 13090]
New array 'b' (swapped back): [ 1 256 8755]
Raw bytes of 'b': 01 00 00 01 33 22

应用:当读取/写入在不同字节序的系统上生成的二进制文件,或者处理某些网络协议或硬件接口时,字节序交换至关重要。

更多详细信息,请参阅 ndarray.byteswap 文档 和 NumPy 中的字节序交换 相关信息。