0

I have big binary bytearray that I want to change from big to little endian of 32 bits

For example b 0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88 to b 0x44,0x33,0x22,0x11,0x88,0x77,0x66,0x55

How can I do that in python?

parser1234
  • 111
  • 1
  • 7
  • `struct.unpack('>', ...)` and then `struct.pack('<', ...)` on the result. More info on [struct](https://docs.python.org/3/library/struct.html) in the docs. – Torxed May 12 '20 at 13:36
  • Does this answer your question? [Convert a Python int into a big-endian string of bytes](https://stackoverflow.com/questions/846038/convert-a-python-int-into-a-big-endian-string-of-bytes) – Torxed May 12 '20 at 13:37
  • Torxed No , that for int , I have big byte array – parser1234 May 12 '20 at 13:38

1 Answers1

1

There are many ways to do this, here is one of them:

data = bytearray(b'\x01\x02\x03\x04\x05\x06\x07\x08')
ref = bytearray(b'\x04\x03\x02\x01\x08\x07\x06\x05')

for offset in range(0, len(data), 4):
    chunk = data[offset:offset + 4]
    if len(chunk) != 4:
        raise ValueError('alignment error')
    data[offset:offset + 4] = chunk[::-1]

assert data == ref

This way you can change the byte order without copying the array.

Pavel
  • 19
  • 3