Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 310
Patrick B. Avatar asked Dec 16 '14 14:12

Patrick B.


People also ask

How do you switch bytes in Python?

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.

How do you convert int to byte in Python?

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.

How do you do a byte swap?

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.

Is int in Python 32 bit?

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.


2 Answers

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

like image 139
Carsten Avatar answered Sep 20 '22 07:09

Carsten


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)) 
like image 33
nos Avatar answered Sep 21 '22 07:09

nos