2

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 advance

asked Nov 5, 2010 at 21:48

2 Answers 2

5

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
answered Nov 6, 2010 at 1:21
Sign up to request clarification or add additional context in comments.

Comments

3

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.

answered Nov 5, 2010 at 21:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.