flip bytes using Python's struct module
-
25-09-2019 - |
Question
I would like to flip from big to little endian this string:
\x00\x40
to have it like this:
\x40\x00
I guess the proper function to use would be struct.pack, but I can't find a way to make it properly work. A small help would be very appreciated !
Thanks
Solution
You're not showing the whole code, so the simplest solution would be:
data = data[1] + data[0]
If you insist on using struct
:
>>> from struct import pack, unpack
>>> unpack('<H', '\x12\x13')
(4882,)
>>> pack('>H', *unpack('<H', '\x12\x13'))
'\x13\x12'
Which first unpacks the string as a little-endian unsigned short, and then packs it back as big-endian unsigned short. You can have it the other way around, of course. When converting between BE and LE it doesn't matter which way you're converting - the conversion function is bi-directional.
OTHER TIPS
data[::-1]
works for any number of bytes.
little_endian = big_endian[1] + big_endian[0]
I could image that what would really want to do here is to convert the input data from big endian (or network) byteorder to your host byteorder (whatever that may be).
>>> from struct import unpack
>>> result = unpack('>H', '\x00\x40')
This would be a more portable approach than just swapping, which is bound to fail when the code is moved to a big endian machine that would not need to swap at all.