Easy Tutorial
❮ Numpy Matrix Numpy Matplotlib ❯

NumPy Byte Swapping

On almost all machines, multi-byte objects are stored as a contiguous sequence of bytes. The byte order is the storage rule for program objects that span multiple bytes.

-

Big-endian mode: Refers to the high-order byte of the data being stored at the lowest memory address, while the low-order byte is stored at the highest memory address. This storage mode is somewhat similar to processing data as a sequential string: addresses increase from small to large, and data is placed from high to low; this is consistent with our reading习惯.

-

Little-endian mode: Refers to the high-order byte of the data being stored at the highest memory address, while the low-order byte is stored at the lowest memory address. This storage mode effectively combines the address高低 and data位权, with high-address parts having a higher权值 and low-address parts having a lower权值.

For example, in C language, a variable x of type int with an address of 0x100, the value of the corresponding address expression &x will be 0x100. The four bytes of x will be stored in the memory locations 0x100, 0x101, 0x102, 0x103.

numpy.ndarray.byteswap()

The numpy.ndarray.byteswap() function swaps the bytes in each element of the ndarray between big-endian and little-endian.

Example

import numpy as np

a = np.array([1, 256, 8755], dtype=np.int16)
print('Our array is:')
print(a)
print('Hexadecimal representation of data in memory:')
print(map(hex, a))
# byteswap() function with True to swap in-place
print('Calling byteswap() function:')
print(a.byteswap(True))
print('Hexadecimal form:')
print(map(hex, a))
# We can see that the bytes have been swapped

Output:

Our array is:
[   1  256 8755]
Hexadecimal representation of data in memory:
<map object at 0x104acb400>
Calling byteswap() function:
[  256     1 13090]
Hexadecimal form:
<map object at 0x104acb3c8>
❮ Numpy Matrix Numpy Matplotlib ❯