开发者

Python Struct, size changed by alignment.

Here's the hex code I am trying to unpack. b'ABCDFGHa\x00a\x00a\x00a\x00a\x00\x00\x00\x00\x00\x00\x01' (it's not supposed to make any sense)

labels = unpack('BBBBBBBHHHHH5sB', msg)
struct.error: unpack requires a bytes argument of length 24

From what I counted, both of those are length = 23, both the format in my unpack function and the length of the hex values. I don't understand.

Thanks in advanc开发者_如何学Pythone


Most processors access data faster when the data is on natural boundaries, meaning data of size 2 should be on even addresses, data of size 4 should be accessed on addresses divisible by four, etc.

struct by default maintains this alignment. Since your structure starts out with 7 'B', a padding byte is added to align the next 'H' on an even address. To prevent this in Python, precede your string with '='.

Example:

>>> import struct
>>> struct.calcsize('BBB')
3
>>> struct.calcsize('BBBH')
6
>>> struct.calcsize('=BBBH')
5


I think H is enforcing 2-byte alignment after your 7 B

Aha, the alignment info is at the top of http://docs.python.org/library/struct.html, not down by the definition of the format characters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜