struct.(un)pack and ASCIIZ strrings

S

Sergey Dorofeev

I can use string.unpack if string in struct uses fixed amount of bytes.
But is there some extension to struct modue, which allows to unpack
zero-terminated string, size of which is unknown?
E.g. such struct: long, long, some bytes (string), zero, short, short,
short.
 
T

Terry Reedy

Sergey Dorofeev said:
I can use string.unpack if string in struct uses fixed amount of bytes.

I presume you mean struct.unpack(format, string). The string len must be
known when you call, but need not be fixed across multiple calls with
different strings.
But is there some extension to struct modue, which allows to unpack
zero-terminated string, size of which is unknown?
E.g. such struct: long, long, some bytes (string), zero, short,
short,short.



Size is easy to determine. Given the above and string s (untested code):
prelen = struct.calcsize('2l')
strlen = s.find('\0', prelen) - prelen
format = '2l %ds h c 3h' % strlen # c swallows null byte

Note that C structs can have only one variable-sized field and only at the
end. With that restriction, one could slice and unpack the fixed stuff and
then directly slice out the end string. (Again, untested)

format = 2l 3h' # for instance
prelen = struct.calcsize(format)
tup = struct.unpack(format, s[:prelen])
varstr = s[prelen, -1] # -1 chops off null byte

Terry J. Reedy
 
J

John Machin

Terry said:
I presume you mean struct.unpack(format, string). The string len must be
known when you call, but need not be fixed across multiple calls with
different strings.



Size is easy to determine. Given the above and string s (untested code):
prelen = struct.calcsize('2l')
strlen = s.find('\0', prelen) - prelen
format = '2l %ds h c 3h' % strlen # c swallows null byte
shouldn't this be '2l %ds c 3h'??
Note that C structs can have only one variable-sized field and only at the
end. With that restriction, one could slice and unpack the fixed stuff and
then directly slice out the end string. (Again, untested)

format = 2l 3h' # for instance
prelen = struct.calcsize(format)
tup = struct.unpack(format, s[:prelen])
varstr = s[prelen, -1] # -1 chops off null byte

Perhaps you meant varstr = s[prelen:-1]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top