Splitting a 32-bit number into separate fields

Is there a quick way in python quickly break a 32-bit variable, say, a1a2a3a4in the a1, a2, a3, a4? I did this by changing the value to hex and then splitting it, but it seems like a waste of time intstringint.

+3
source share
4 answers

The standard library module struct does a short job:

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

A “package” with a format '>I'makes it xinto a 4-byte string in big-endian order, which can immediately be “unpacked” into four values ​​without a signed byte with the format '4B'. Easy peasy.

+13

Python , 32- . , ?

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

SilentGhost, int, :

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

, Python longs, x , 0x7fffffff ints . int. Python : unified, .

+6

.

:

myvar = 0xcdf100cd
a0 = myvar & 0xff
a1 = (myvar >> 8) & 0xff
a2 = (myvar >> 16) & 0xff
a3 = (myvar >> 24) & 0xff

the &0xff 8 , - (>>) , 8 .

+4

A little late, but I usually do something like this:

hexnum = 0xa1a2a3a4
bytes = []
while (hexnum > 0):
    bytes.insert(0, hexnum & 0xff)
    hexnum >>= 8

Not sure if it is more efficient then unzip it or not (most likely not because of using list.insert ()).

0
source

Source: https://habr.com/ru/post/1730042/


All Articles