Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 957
dantje Avatar asked Mar 13 '11 11:03

dantje


1 Answers

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)))
like image 195
Fred Foo Avatar answered Sep 25 '22 19:09

Fred Foo