A
A
Alexander2020-02-04 17:58:18
Python
Alexander, 2020-02-04 17:58:18

Why does sruct.unpack require more bytes?

there is a sequence (structure) of 14 bytes
there are 6 variables
uint32 = 4 bytes
uint8 = 1 byte
uint8 = 1 byte
uint32 = 4 bytes
uint16 = 2 bytes
uint16 = 2 bytes
4+1+1+4+2+2 = 14 bytes in sum
According to https://docs.python.org/3/library/struct.html
I = 4
B = 1
B = 1
I = 4 (jumps from 6 to 12 when added but 6+4=10)
H = 2
H = 2
I get but with H = 2 x = 1 x = 1 it works, not counting the loss of 2 high bytes from the 4th variable struct.unpack("IBBIHH",data)
struct.error: unpack requires a buffer of 16 bytes

struct.unpack("IBBHxxHH",data)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2020-02-04
@NeiroNx

Specify byte order:

In [2]: s.pack("IBBIHH", 1, 2, 3, 4, 5, 6)                                                                              
Out[2]: b'\x01\x00\x00\x00\x02\x03\x00\x00\x04\x00\x00\x00\x05\x00\x06\x00'

In [3]: len(s.pack("IBBIHH", 1, 2, 3, 4, 5, 6))                                                                         
Out[3]: 16


In [8]: s.pack(">IBBIHH", 1, 2, 3, 4, 5, 6)                                                                             
Out[8]: b'\x00\x00\x00\x01\x02\x03\x00\x00\x00\x04\x00\x05\x00\x06'

In [9]: len(s.pack(">IBBIHH", 1, 2, 3, 4, 5, 6))                                                                        
Out[9]: 14

Otherwise, read about alignment:
Note By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.

https://docs.python.org/3/library/struct.html#byte...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question