What would the best way of unpacking a python string into fields
I have data received from a tcp socket, it is packed as follows, I believe it will be in a string from the socket recv function
It has the following format
uint8 – header
uint8 – length
uint32 – typeID
uint16 -param1
uint16 -param2
uint16 -param3
uint16 -param4
char[24] – name string
uint32 – checksum
uint8 – footer
(I also need to unpack other packets with different formats to the above)
How do I unpack these?
I am new to python, have done a bit of ‘C’. If I was using ‘C’ I would probably use a structure, would this be the way to go with Python?
Regards
X
The struct module is designed to unpack heterogeneous data to a tuple based on a format string. It makes more sense to unpack the whole struct at once rather than trying to pull out one field at a time. Here is an example:
Then you can access a given field, for example the first field:
You could also use the tuple to initialize a NamedTuple; look at the documentation for struct for an example. NamedTuples are only available in Python 2.6+, but they behave more like Python structures in that you can access elements as attributes, e.g. fields.header. Of course, you could also accomplish this with a little more work by writing a class to encapsulate the information from the tuple… again, if you care. You can always just index into fields directly, as I showed above.