NumPy Tutorial NumPy Statistics NumPy References

NumPy - Byte Swapping



The ndarray is an object that provide a python array interface to data in memory and the memory of a computer depends on which architecture the CPU uses. It often happens that the memory that a user wants to view with an array is not of the same byte ordering as the computer on which the user is running Python.

For example, a user might be working on a computer with a little-endian CPU - such as an Intel Pentium, but has loaded some data from a file written by a computer that is big-endian. Let’s say a user has loaded 4 bytes from a file written by a Sun (big-endian) computer. As it is known that these 4 bytes represent two 16-bit integers. On a big-endian machine, a two-byte integer is stored with the Most Significant Byte (MSB) first, and then the Least Significant Byte (LSB). Thus the bytes are, in memory order:

  • MSB integer 1
  • LSB integer 1
  • MSB integer 2
  • LSB integer 2

ndarray.byteswap() function

The NumPy ndarray.byteswap() function swaps the bytes of the array elements. It toggles between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.

Syntax

numpy.ndarray.byteswap(inplace=False)

Parameters

inplace Optional. If True, swap bytes in-place, default is False.

Return Value

Returns the byteswapped array. If inplace is True, this is a view to self.

Example:

In the example below, the ndarray.byteswap() function is used to to toggle between low-endian and big-endian data representation

import numpy as np

Arr = np.array([1, 256, 8755], dtype=np.int16)
print("Arr is:")
print(Arr)

#displaying the data in memory in 
#hexadecimal form
print("\nData in memory in hexadecimal form")
print(list(map(hex,Arr)))

#using byteswap() function to toggle between 
#low-endian and big-endian data representation
Arr.byteswap(inplace=True)

#after applying byteswap() function
print("\nAfter applying byteswap() function, Arr is:")
print(Arr)

#displaying the data in memory in 
#hexadecimal form
print("\nData in memory in hexadecimal form")
print(list(map(hex,Arr)))

The output of the above code will be:

Arr is:
[   1  256 8755]

Data in memory in hexadecimal form
['0x1', '0x100', '0x2233']

After applying byteswap() function, Arr is:
[  256     1 13090]

Data in memory in hexadecimal form
['0x100', '0x1', '0x3322']