I'm trying to do byte-swapping using NumPy in Python.
I've created the function swap32() which byte swaps the bytes representation of the array that is composed of 32-bit ints. I provide a little-endian bytes object (brr) as the input in the code below and then the function swap it's bytes to convert it to big-endian. The output that my code produces is shown below (which is wrong btw).
>>> import numpy as np
>>> def swap32(x):
... y = bytearray(x)
... a = np.array(y, dtype=np.uint32)
... return bytes(a.byteswap())
>>> arr = [1,2,3,4,5]
>>> brr = bytes(arr)
>>> brr
b'\x01\x02\x03\x04\x05'
>>> swap32(brr)
b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05'
If I byteswap brr again then I get the following result which is incorrect because a swap32(swap32(brr)) should give back original brr.
>>> swap32(y)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05'
I'm certainly going wrong somewhere which I'm unable to figure out. Isn't there any standard way (or easy way) to swap bytes of a bytes object in Python?
bytes([1,2,3,4,5])is not 32-bits in any sense that I can figure\x00\x00\x00\x01.bytesobject is not 32 bits. What I meant to say is that I have a bytes object and I want to do byteswapping assuming that the array is made of 32bit ints.I'm updating the post. My apologies.