views:

121

answers:

3

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

+4  A: 

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.

Eli Bendersky
A: 

little_endian = big_endian[1] + big_endian[0]

Josh Matthews
+3  A: 

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

Paul Hankin
I think this is a much better way to do it.
Matt Joiner