Python – How to byte-swap a 32-bit integer in python

endiannessintegerpython

Take this example:

i = 0x12345678
print("{:08x}".format(i))
   # shows 12345678
i = swap32(i)
print("{:08x}".format(i))
   # should print 78563412

What would be the swap32-function()? Is there a way to byte-swap an int in python, ideally with built-in tools?

Best Solution

One method is to use the struct module:

def swap32(i):
    return struct.unpack("<I", struct.pack(">I", i))[0]

First you pack your integer into a binary format using one endianness, then you unpack it using the other (it doesn't even matter which combination you use, since all you want to do is swap endianness).