Open In App

NumPy ndarray.byteswap() Method | Swap bytes of the Array Elements

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python program explaining 
# byteswap() function 
import numpy as geek
  
# a is an array of integers.
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
  
# Create a NumPy array of float64 type
A = np.array([1.5, 2.5, 3.5], dtype=np.float64)
print(A)  # Output: [1.5 2.5 3.5]
  
# Byteswap the array
A.byteswap(inplace=True)
  
# Print the byteswapped array
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 is an array of strings
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'


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads