Structures and Unpacking in Python

I tried to understand how unpacking works. More specifically, this specific example in the documentation is confusing because it will not give me the same result when I introduce it in the exact same way. https://docs.python.org/2/library/struct.html#struct-examples

>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')
8

An 8-byte size makes sense, but when I do calcsize ('hhl'), it returns 16. Keeping the package ('hhl', 1, 2, 3) as a variable and unpacking it works fine, but using hexadecimal values, I get the error "unpack requires a string argument of length 16", any idea what is the problem? Thanks

+4
source share
2 answers

:

>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'

[ \, x, 0,...], bytearray, , hex:

>>> pack('hhl', 1, 2, 3)[0]
'\x00'

, :

>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')

, . :

>>> s = pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', s)
(1, 2, 3)

.

, @falstru, bytearray, , binascii.unhexlify, . :

>>> unpack('hhl', str(bytearray([1,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0])))
(1, 2, 3)
+2

'0001000200000003', , binascii.unhexlify ( binascii.a2b_hex)

>>> import struct
>>> import binascii
>>> struct.unpack('>hhl', binascii.unhexlify('0001000200000003'))
(1, 2, 3)
+1

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


All Articles