|
| 1 | +--- |
| 2 | +title: numpy.ndarray.byteswap |
| 3 | +description: Modifies the byte order (endianness) of the array elements in place or returns a copy with swapped bytes. |
| 4 | +keywords: numpy, ndarray, byteswap, endian, endianness, byte order, data representation |
| 5 | +type: method |
| 6 | +--- |
| 7 | + |
| 8 | +The **`.byteswap()`** method reverses the byte order (endianness) of each element in a NumPy array. It's used to ensure data compatibility between systems with different byte storage conventions (little-endian vs. big-endian). |
| 9 | + |
| 10 | +--- |
| 11 | + |
| 12 | +## Syntax |
| 13 | + |
| 14 | +```python |
| 15 | +array_instance.byteswap(inplace=False) |
| 16 | + |
| 17 | +## Example |
| 18 | +Consider an array of 16-bit integers (`np.int16`). On common systems (like Intel/AMD using little-endian), the number 256 is stored with its bytes as `00 01`. Calling `.byteswap()` reverses these bytes to `01 00`. If this swapped byte sequence is interpreted using the original little-endian data type, it represents a different numerical value. |
| 19 | + |
| 20 | +### Return Value |
| 21 | +Returns either the modified original array (if `inplace=True`) or a new array with the byte order swapped (if `inplace=False`). The data type (`dtype`) of the returned array may reflect the new byte order depending on the system and NumPy version, but the underlying byte sequence is always swapped. |
| 22 | + |
| 23 | +import numpy as np |
| 24 | + |
| 25 | +# Create an array of 16-bit integers (usually little-endian by default) |
| 26 | +# 256 in little-endian bytes: 00 01 |
| 27 | +original_array = np.array([1, 256, 512], dtype=np.int16) |
| 28 | +print(f"Original array: {original_array}") |
| 29 | +print(f"Original dtype: {original_array.dtype}") |
| 30 | +print(f"Original bytes (hex): {original_array.tobytes().hex()}") |
| 31 | + |
| 32 | +# Swap bytes, returning a NEW array (inplace=False is default) |
| 33 | +swapped_array = original_array.byteswap() |
| 34 | + |
| 35 | +print("\n--- After byteswap() ---") |
| 36 | +# Values change because the raw bytes are swapped but interpreted via original dtype order |
| 37 | +print(f"Swapped array values (interpreted): {swapped_array}") |
| 38 | +print(f"Swapped array dtype: {swapped_array.dtype}") |
| 39 | +print(f"Swapped bytes (hex): {swapped_array.tobytes().hex()}") # Bytes reversed per element (e.g., 0001 -> 0100) |
| 40 | + |
| 41 | +# Swap bytes IN PLACE |
| 42 | +print("\n--- In-place swap ---") |
| 43 | +# The method returns the modified array when inplace=True |
| 44 | +modified_original = original_array.byteswap(inplace=True) |
| 45 | +print(f"Original array after in-place swap: {original_array}") |
| 46 | +print(f"Return value (inplace=True): {modified_original}") # It's the same array object |
| 47 | +print(f"Original array bytes after swap (hex): {original_array.tobytes().hex()}") |
| 48 | +``` |
0 commit comments