beratch
beratch

Reputation: 287

flip bytes using Python's struct module

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

Upvotes: 1

Views: 5138

Answers (4)

dantje
dantje

Reputation: 1779

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.

Upvotes: 0

user97370
user97370

Reputation:

data[::-1] works for any number of bytes.

Upvotes: 6

Eli Bendersky
Eli Bendersky

Reputation: 273546

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.

Upvotes: 6

Josh Matthews
Josh Matthews

Reputation: 13026

little_endian = big_endian[1] + big_endian[0]

Upvotes: 0

Related Questions