How to unpack 6 bytes as a whole using struct in Python

I have the following 8 bytes:

b'\x05\x00\x00\x00\x00\x00\x05\x00' 

I am trying to get two integers using struct.unpack: one for the first 2 bytes and one for the last 6. Getting the first two is easy with:

 struct.unpack("<H6B") 

But it returns

 (5, 0, 0, 0, 0, 5, 0) 

I want it to return the following:

 (5, 5) 

How to get integer value from last 6 bytes? I do not want each byte to be individual.

+6
source share
2 answers

struct does not support non-two-two integers. This is a common occurrence. C does not support such integers on your platform (well, bit fields, but you cannot create an array of them).

 def unpack48(x): x1, x2, x3 = struct.unpack('<HHI', x) return x1, x2 | (x3 << 16) 
+11
source

The standard structural module does not support all possible sizes, so you need to either combine several bits (see Dietrich's answer), or you can use external modules such as bitstring .

 >>> from bitstring import BitArray >>> b = BitArray(bytes=b'\x05\x00\x00\x00\x00\x00\x05\x00') >>> b.unpack('<H6B') [5, 0, 0, 0, 0, 5, 0] 

which is consistent with the standard struct.unpack . But now we can instead unpack the second element as a 6-byte (48-bit) unsigned unsigned integer:

 >>> b.unpack('<H, uintle:48') [5, 21474836480] 

which gives you the same result as Dietrich’s answer, and also shows that you have something wrong with your question! What do you need in this case:

 >>> b.unpack('uintle:48, <H') [5, 5] 

Note that you could also write <H as uintle:16 if you need a more consistent write.

+4
source

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


All Articles