Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

breaking a 32-bit number into individual fields

Tags:

python

Is there a quick way in python to split a 32-bit variable, say, a1a2a3a4 into a1, a2, a3, a4 quickly? I've done it by changing the value into hex and then splitting it, but it seems like a waste of time doing int->string->int.

like image 275
calccrypto Avatar asked Nov 28 '22 23:11

calccrypto


2 Answers

Standard library module struct does short work of it:

>>> import struct
>>> x = 0xa1a2a3a4
>>> struct.unpack('4B', struct.pack('>I', x))
(161, 162, 163, 164)

"packing" with format '>I' makes x into a 4-byte string in big-endian order, which can then immediately be "unpacked" into four unsigned byte-size values with format '4B'. Easy peasy.

like image 103
Alex Martelli Avatar answered Dec 06 '22 08:12

Alex Martelli


There isn't really such thing as a 32-bit variable in Python. Is this what you mean?

x = 0xa1a2a3a4
a4 = int(x & 0xff)
a3 = int((x >> 8) & 0xff)
a2 = int((x >> 16) & 0xff)
a1 = int(x >> 24)

As SilentGhost points out, you don't need the int conversion, so you can do this:

a4 = x & 0xff
a3 = (x >> 8) & 0xff
a2 = (x >> 16) & 0xff
a1 = x >> 24

Note that in older versions of Python, the second version will return longs if the value of x is greater than 0x7fffffff and ints otherwise. The first version always returns int. In newer versions of Python the two types are unified so you don't have to worry about this detail.

like image 30
Mark Byers Avatar answered Dec 06 '22 07:12

Mark Byers