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?
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With