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?
One method is to use the
struct
module: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).
From python 3.2 you can define function swap32() as the following:
It uses array of bytes to represent the value and reverses order of bytes by changing endianness during conversion back to integer.
Big endian means the layout of a 32 bit int has the most significant byte first,
e.g. 0x12345678 has the memory layout
while on little endian, the memory layout is
So you can just convert between them with some bit masking and shifting: