Python structure error

I am trying to create a system to respond to different binary flags.

0 = Error
1 = Okay
2 = Logging
3 = Number

The sequence of this data represents a unique identifier for the job reference, flag, and number. Everything works except the number flag. This is what I get ...

>>> import struct
>>> data = (1234, 3, 12345678)
>>> bin = struct.pack('QHL', *data)
>>> print(bin)
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00Na\xbc\x00\x00\x00\x00\x00'
>>> result = struct.unpack_from('QH', bin, 0)
>>> print(result)
(1234, 3)
>>> offset = struct.calcsize('QH')
>>> result += struct.unpack_from('L', bin, offset)
>>> print(result)
(1234, 3, 7011541669862440960)

Must be large enough to represent a number 12345678, but why is it unpacked incorrectly?

Edit:

When I try to pack them separately, it looks like the struct adds too many null bytes between the flag and the long one.

>>> import struct
>>> struct.pack('QH', 1234, 3)
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x03\x00'
>>> struct.pack('L', 12345678)
b'Na\xbc\x00\x00\x00\x00\x00'

I can reproduce this error by adding an addition to the long one.

>>> struct.unpack('L', struct.pack('L', 12345678))
(12345678,)
>>> struct.unpack('xL', struct.pack('xL', 12345678))
(12345678,)
>>> struct.pack('xL', 12345678)
b'\x00\x00\x00\x00\x00\x00\x00\x00Na\xbc\x00\x00\x00\x00\x00'

Potential fix?

little-endian , , , . SSL- TCP-, , ? , , ?

>>> import struct
>>> data = (1234, 3, 12345678)
>>> bin = struct.pack('<QHL', *data)
>>> print(bin)
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x03\x00Na\xbc\x00'
>>> result = struct.unpack_from('<QH', bin, 0)
>>> print(result)
(1234, 3)
>>> offset = struct.calcsize('<QH')
>>> result += struct.unpack_from('<L', bin, offset)
>>> print(result)
(1234, 3, 12345678)

? .

+4
3

. , , . , , .

, struct.calcsize, , :

>>> struct.calcsize('QHL')
16
>>> struct.calcsize('QH')
10

, QHL 16 , QH 10. L , 4 . , , , L " ". , ( ), , . QH :

QQ QQ | QQ QQ | HH

QHL :

QQ QQ | QQ QQ | HH 00 | LL LL

, , , L .

( endianness) . =QHL :

QQ QQ | QQ QQ | HH LL | LL

little-endian , , , . SSL- TCP-, , ? , , ?

, . , . - , .

+6

:

>>> import struct
>>> data = (1234, 3, 12345678)
>>> bin = struct.pack('QHL', *data)
>>> print(bin)
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00Na\xbc\x00\x00\x00\x00\x00'
>>> result = struct.unpack_from('QH', bin, 0)
>>> print(result)
(1234, 3)
>>> result += struct.unpack_from('L', bin, 16)
>>> print(result)
(1234, 3, 12345678)

, :

.

, , :

, . '<,' > , '=, '!.

+1

This is a byte alignment problem. In your case, the next replacement will give you the correct result.

result += struct.unpack_from('L', bin, offset+2)
+1
source

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


All Articles