reallcoder
reallcoder

Reputation: 55

Python Struct format error

So I am looking at code that I wrote perhaps as much as 4 years ago, and I know it ran correctly at the time. But now I am trying to run it, on a different computer than when I wrote it years ago and I am getting an error now. (Tried it today on both Windows 10 and Ubuntu)

I am using Python 2.7, as I was then too. I am using the Struct library to unpack C types from files, specifically I am trying to unpack 4 byte long values. Here is the documentation for the 2.7 struct library. https://docs.python.org/2/library/struct.html

If you scroll down to the "Format Characters" section, you can see a table of the C types.

Here is my code:

bps = int(unpack('L', fmap[o+10:o+14])[0])

And here is the error I get.

error: unpack requires a string argument of length 8

The part that is confusing me is the "length 8" part. If I change the C type to "I" the code executes fine. But the documentation seems clear that "L" is 4 byte as well, and it worked in the past. I think I can use the "I" type for my purposes, but I am curious if any one else has seen this.

Upvotes: 1

Views: 139

Answers (1)

chepner
chepner

Reputation: 531808

The standard size of L is 4 bytes, but that is only used if you are explicit about the endianness to use by beginning the format string with >, <, !, or =. Otherwise, the platform-dependent native size for your machine is used. (In this case, 8 bytes.)

Upvotes: 3

Related Questions