[python] struct.error: unpack requires a string argument of length 4

Python says I need 4 bytes for a format code of "BH":

struct.error: unpack requires a string argument of length 4

Here is the code, I am putting in 3 bytes as I think is needed:

major, minor = struct.unpack("BH", self.fp.read(3))

"B" Unsigned char (1 byte) + "H" Unsigned short (2 bytes) = 3 bytes (!?)

struct.calcsize("BH") says 4 bytes.

EDIT: The file is ~800 MB and this is in the first few bytes of the file so I'm fairly certain there's data left to be read.

This question is related to python struct

The answer is


By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.

To disable this, use: struct.unpack("=BH", data). This will use standard alignment, which doesn't add padding:

>>> struct.calcsize('=BH')
3

The = character will use native byte ordering. You can also use < or > instead of = to force little-endian or big-endian byte ordering, respectively.