Packing data of different sizes into a list of unsigned ints

一曲冷凌霜 提交于 2019-12-06 06:40:24

You are using the right tool, but you told pack to encode 2 arguments, but pass in only one.

The string HB means: pack two values, one as an unsigned short, the other as an unsigned byte. Pass in two values and it works:

>>> pack('HB', 0x0506, 0x07)
'\x06\x05\x07'

Just keep experimenting, you'll get the hang of it. Here are the first set of values from your example, in Big Endian notation:

>>> pack('>2H20c40c', 0x0102, 0x0304)
'\x01\x02\x03\x04AStrWith20CharactersWoahThisStringHas40CharactersItIsHuge!!!'

Note the '>' at the start, this signals the endianess. The strings are converted to sequences and applied as individual variables. Generally, it's easier to just append them though:

>>> pack('>2H20c40c', 0x0102, 0x0304) + "AStrWith20Characters" + "WoahThisStringHas40CharactersItIsHuge!!!"
'\x01\x02\x03\x04AStrWith20CharactersWoahThisStringHas40CharactersItIsHuge!!!'

You can pack the whole thing using your struct format, and unpack it using the e.g. 32-bit words format:

>>> format="cchi"
>>> p=pack(format,"a","b",1,2)
>>> p
'ab\x01\x00\x02\x00\x00\x00'
>>> (z1,z2)=unpack("ii",p)
>>> (z1,z2)
(90721, 2)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!