Struggling with struct.unpack() and "p" format specifier
peter at engcorp.com
Tue Nov 30 16:48:51 CET 2004
> As I mentioned, I can parse the string and read it with multiple
> statements, I am just looking for a more efficient solution.
This looks like about the best you can do, using the information
from Tim's reply:
>>> buf = '\0\0\xb9\x02\x13EXCLUDE_CREDIT_CARD'
>>> import struct
>>> x = struct.unpack('>xxBB%sp' % (ord(buf)+1), buf)
(185, 2, 'EXCLUDE_CREDIT_CARD')
If you wanted to avoid hard-coding the 4, you would
be most correct to do this:
header = '>xxBB'
lenIndex = struct.calcsize(header)
x = struct.unpack('%s%dp' % (header, ord(buf[lenIndex])+1), buf)
... though that doesn't exactly make it all that readable.
More information about the Python-list