NeiroNx
@NeiroNx
Программист

Почему sruct.unpack требует больше байт?

есть последовательность(структура) из 14 байт
там 6 перемнных
uint32 = 4 байта
uint8 = 1 байт
uint8 = 1 байт
uint32 = 4 байта
uint16 = 2 байта
uint16 = 2 байта
4+1+1+4+2+2 = 14 байт в сумме
Судя по https://docs.python.org/3/library/struct.html
I = 4
B = 1
B = 1
I = 4 (при добавлении перескакивает с 6 на 12 но 6+4=10)
H = 2
H = 2
получаю struct.unpack("IBBIHH",data)
struct.error: unpack requires a buffer of 16 bytes

но с
H = 2
x = 1
x = 1
struct.unpack("IBBHxxHH",data)
работает, не считая потери 2 старших байт от 4 переменной
  • Вопрос задан
  • 5060 просмотров
Решения вопроса 1
@deliro
Укажи 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


Иначе читай про выравнивание:

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...
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы