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?
byteswap() function toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Parameters: inplace : [bool, optional] If True, swap bytes in-place, default is False.
An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.
Given a byte, swap the two nibbles in it. For example 100 is be represented as 01100100 in a byte (or 8 bits). The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal.
The int data type in python simply the same as the signed integer. A signed integer is a 32-bit integer in the range of -(2^31) = -2147483648 to (2^31) – 1=2147483647 which contains positive or negative numbers.
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).
Big endian means the layout of a 32 bit int has the most significant byte first,
e.g. 0x12345678 has the memory layout
msb lsb +------------------+ | 12 | 34 | 56 | 78| +------------------+
while on little endian, the memory layout is
lsb msb +------------------+ | 78 | 56 | 34 | 12| +------------------+
So you can just convert between them with some bit masking and shifting:
def swap32(x): return (((x << 24) & 0xFF000000) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | ((x >> 24) & 0x000000FF))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With