Numpy 简明教程

NumPy - Byte Swapping

我们已经看到,计算机内存中存储的数据取决于CPU使用的哪种架构。它可能是小端(最低有效位存储在最小地址中)或大端(最高有效字节在最小地址中)。

numpy.ndarray.byteswap()

numpy.ndarray.byteswap() 函数在两种表示形式之间切换:大端和小端。

import numpy as np
a = np.array([1, 256, 8755], dtype = np.int16)

print 'Our array is:'
print a

print 'Representation of data in memory in hexadecimal form:'
print map(hex,a)
# byteswap() function swaps in place by passing True parameter

print 'Applying byteswap() function:'
print a.byteswap(True)

print 'In hexadecimal form:'
print map(hex,a)
# We can see the bytes being swapped

它将生成如下输出:

Our array is:
[1 256 8755]

Representation of data in memory in hexadecimal form:
['0x1', '0x100', '0x2233']

Applying byteswap() function:
[256 1 13090]

In hexadecimal form:
['0x100', '0x1', '0x3322']