Inspect byte order before using array.byteswap
Python’s array stores machine-format values. byteswap() reverses the bytes inside each item in place; it does not attach an endianness label to the array.
Run the example
Tested on Linux with Python 3.12.14. No third-party packages or network access are needed. In one Bash session, create a temporary working directory:
demo_start="$PWD"
demo_dir="$(mktemp -d)" || exit 1
cd -- "$demo_dir" || exit 1Save as demo_array_byte_order.py in that directory. Use this filename to avoid shadowing a standard-library module.
from array import array
import sys
values = array("H", [0x1234, 0xABCD])
if values.itemsize != 2:
raise RuntimeError("This example requires two-byte unsigned shorts")
original = values.tobytes()
print("Native byte order:", sys.byteorder)
print("Original bytes:", original.hex())
values.byteswap()
print("Swapped bytes:", values.tobytes().hex())
print("Numeric values:", [hex(value) for value in values])
values.byteswap()
print("Restored:", values.tobytes() == original)Run it:
python3 demo_array_byte_order.pyCaptured output:
Native byte order: little
Original bytes: 3412cdab
Swapped bytes: 1234abcd
Numeric values: ['0x3412', '0xcdab']
Restored: TrueInterpret the result
The swap changes both the stored bytes and the numbers interpreted in native byte order. Swapping again restores the original bytes. The explicit item-size check prevents this example from silently assuming a fixed width for the platform’s unsigned short. On a machine with different byte order, the first two byte strings differ from this Linux capture. For an external format, specify its width and byte order explicitly, for example with struct, rather than assuming array.tobytes() is portable. Everything here remains in memory.
See the version-specific Python reference for the API contract.
Clean up
In the same Bash session, remove the source file and then the empty working directory:
rm -- demo_array_byte_order.py
cd -- "$demo_start" || exit 1
rmdir -- "$demo_dir"
unset demo_start demo_dirIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.