How to byte-swap a 32-bit integer in python?

Patrick B. picture Patrick B. · Dec 16, 2014 · Viewed 40.2k times · Source

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?

Answer

Carsten picture Carsten · Dec 16, 2014

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).