5

When using the python struct module on can specify a format string that declares how binary data should be interpreted:

>>> from struct import *
>>> fmt = 'hhl'
>>> values = [1,2,3]
>>> blob = pack(fmt, values)

It is easily possible to calculate the amount of bytes needed to store an instance of that format:

>>> calcsize(fmt)

What would be the best way to retrieve the number of variables need to 'fill' a format? Basically this would tell in advance how big the 'values' array should be to perform the pack() in the above example.

>>> calcentries(fmt)
3

Is there such a thing?

dantje
  • 1,739
  • 1
  • 13
  • 25

1 Answers1

5

I'm afraid there's no such function in the struct API, but you can define it yourself without parsing the format string:

def calcentries(fmt):
    return len(struct.unpack(fmt, '\0' * struct.calcsize(fmt)))
Fred Foo
  • 355,277
  • 75
  • 744
  • 836