NumPy Byte Swapping

In almost all machines, multi-byte objects are stored as consecutive byte sequences. Byte order is the storage rule for program objects that span multiple bytes.

  • Big-endian mode:Refers to the high-order byte of data being stored at the low memory address, while the low-order byte is stored at the high memory address. This storage mode is somewhat like treating data as a string in order: addresses increase from small to large, while data is placed from high to low; this is consistent with our reading habits.

  • Little-endian mode:Refers to the high-order byte of data being stored at the high memory address, while the low-order byte is stored at the low memory address. This storage mode effectively combines the address level with the data bit weight: the high address part has a high weight, and the low address part has a low weight.

For example, in C language, an int variable x has address 0x100, so the value of its corresponding address expression &x is 0x100. The four bytes of x will be stored at memory positions 0x100, 0x101, 0x102, 0x103.

numpy.ndarray.byteswap()

The numpy.ndarray.byteswap() function converts the byte order of each element in an 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 ('Display the data in memory in hexadecimal:') print (map(hex,a)) # byteswap() function swaps in place by passing True print ('Call the byteswap() function:') print (a.byteswap(True)) print ('Hexadecimal form:') print (map(hex,a)) # We can see that the bytes have been swapped

Output result:

我们的数组是:
[   1  256 8755]
以十六进制表示内存中的数据:
<map object at 0x104acb400>
调用 byteswap() 函数:
[  256     1 13090]
十六进制形式:
<map object at 0x104acb3c8>
Other extensions