English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NumPy Byte Swapping

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

Little-endian mode:The high byte of the data is stored at the high address of the memory, while the low byte of the data is stored at the low address of the memory. This storage mode effectively combines the address level and the bit weight of the data, with the high address part having a higher weight and the low address part having a lower weight.

For example, in C language, an int variable x with address 0x100, then the corresponding address expression &x is 0x100. And the four bytes of x will be stored in memory at the address 0x100, 0x101, 0x102, 0x103Position.

numpy.ndarray.byteswap()

The numpy.ndarray.byteswap() function performs endianness conversion on each byte of the elements in the ndarray.

 import numpy as np 
 a = np.array([1, 256, 8755], dtype = np.int16) 
 print('Our array is: ')
 print(a)
 print('Represent the data in memory in hexadecimal: ')
 print(map(hex, a))
 # The byteswap() function swaps the endianness of each element in the ndarray 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
 Our array is:
 [ 1 256 8755]
 Represent the data in memory in hexadecimal:
 <map object at 0x104acb400>
 Call the byteswap() function:
 [ 256 1 13090]
 Hexadecimal Form:
 <map object at 0x104acb3c8>