NumPy ndarray.byteswap() Method | Swap bytes of the Array Elements
Last Updated :
05 Feb, 2024
The ndarray.byteswap() method 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.
Note: byteswap() method does not work on arrays of strings.
Example
Python3
import numpy as geek
a = geek.array([ 1 , 256 , 100 ], dtype = np.int16)
print (a.byteswap( True ))
|
Output
[256 1 25600]
Syntax
Syntax: ndarray.byteswap(inplace=False)
Parameters
- inplace : [bool, optional] If True, swap bytes in-place, default is False.
Returns
- out : [ndarray] The byteswapped array. If inplace is True, this is a view to self.
How to swap the byte order of the data in the ndarray
To toggle between low-endian and big-endian data representation we use ndarray.byteswap() method of NumPy library.
This is useful when the data has been written in a machine with a different byte order than the one where it is being read.
Let’s understand it better with an example:
Example 1:
Python3
import numpy as np
A = np.array([ 1.5 , 2.5 , 3.5 ], dtype = np.float64)
print (A)
A.byteswap(inplace = True )
print (A)
|
Output:
[1.5 2.5 3.5]
[3.13984e-319 5.37543e-321 1.54939e-320]
Example 2:
byteswap() method raises error when the array contains string elements.
Python3
import numpy as geek
a = geek.array([ "arka" , "soumen" , "simran" ],dtype = np.int16)
print (a.byteswap( True ))
|
Output :
ValueError Traceback (most recent call last)
in ()
1 import numpy as geek
----> 2 a = geek.array(["arka","soumen","simran"],dtype = np.int16)
3
4 #a is an array of strings
5
ValueError: invalid literal for int() with base 10: 'arka'
Share your thoughts in the comments
Please Login to comment...