numpy.ndarray.byteswap#
method
- ndarray.byteswap(inplace=False)#
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation byreturning a byteswapped array, optionally swapped in-place.Arrays of byte-strings are not swapped. The real and imaginaryparts of a complex number are swapped individually.
- Parameters:
- inplacebool, optional
If
True, swap bytes in-place, default isFalse.
- Returns:
- outndarray
The byteswapped array. Ifinplace is
True, this isa view to self.
Examples
>>>importnumpyasnp>>>A=np.array([1,256,8755],dtype=np.int16)>>>list(map(hex,A))['0x1', '0x100', '0x2233']>>>A.byteswap(inplace=True)array([ 256, 1, 13090], dtype=int16)>>>list(map(hex,A))['0x100', '0x1', '0x3322']
Arrays of byte-strings are not swapped
>>>A=np.array([b'ceg',b'fac'])>>>A.byteswap()array([b'ceg', b'fac'], dtype='|S3')
A.view(A.dtype.newbyteorder()).byteswap()produces an array withthe same values but different representation in memory>>>A=np.array([1,2,3],dtype=np.int64)>>>A.view(np.uint8)array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0], dtype=uint8)>>>A.view(A.dtype.newbyteorder()).byteswap(inplace=True)array([1, 2, 3], dtype='>i8')>>>A.view(np.uint8)array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3], dtype=uint8)
On this page