Determine the number of elements in a python string struct / pack fmt?

When using the struct python on module, you 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)

You can easily calculate the number of bytes needed to store an instance of this format:

>>> calcsize(fmt)

What would be the best way to get the number of variables, do you need to “fill out” the format? Basically, this informed in advance how large an array of “values” the package () should execute in the above example.

>>> calcentries(fmt)
3

Is there such a thing?

+5
source share
1 answer

, API struct , :

def calcentries(fmt):
    return len(struct.unpack(fmt, '\0' * struct.calcsize(fmt)))
+5

All Articles