Struggling with struct.unpack() and "p" format specifier

Peter Hansen peter at engcorp.com
Tue Nov 30 10:48:51 EST 2004


Geoffrey wrote:
> 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[4])+1), buf)
 >>> x
(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.

-Peter



More information about the Python-list mailing list