pack/unpack zero terminated string

John Machin sjmachin at lexicon.net
Wed May 2 17:13:45 EDT 2007


On May 3, 12:01 am, Laurent Pointal <laurent.poin... at limsi.fr> wrote:
> tmp123 a écrit :
>
> > Hello,
>
> > Thanks for your time.
>
> > After review the "struct" documentation, it seems there are no option
> > to pack/unpack zero terminated strings.
>
> > By example, if the packed data contains: byte + zero terminated string
> > + zero terminated string + byte, it seems no possible to unpack it
> > using "struct".
>
> > Please, has someone any hint or pointer to another librarian to be
> > used?
>
> May look at xstruct too
>
> http://www.sis.nl/python/xstruct/xstruct.shtml

Hi, Laurent,

It's a reasonable presumption that the OP needs to unpack *variable-
length* zero-terminated strings, otherwise why is he asking? This
would need a new format type e.g. "z".

xstruct doesn't appear to offer variable-length strings, and is frozen
in time (October 1999) -- inspection of the source shows that it is a
copy of Python 1.5.2 structmodule.c with added stuff.

The OP might like to try a bit of DIY in Python, along the following
lines:

C:\junk>type unpackz.py
def getz(strg, start=0):
    zpos = strg.index('\0', start)
    return strg[start:zpos], zpos + 1

def getB(strg, start=0):
    return ord(strg[start]), start + 1

def unpack_BzzB(strg):
    pos = 0
    r0, pos = getB(strg, pos)
    r1, pos = getz(strg, pos)
    r2, pos = getz(strg, pos)
    r3, pos = getB(strg, pos)
    assert pos == len(strg)
    return r0, r1, r2, r3

x = chr(42) + 'foo\0' + 'mumble\0' + '\xff'
print unpack_BzzB(x)
print unpack_BzzB('\0' * 4)

C:\junk>unpackz.py
(42, 'foo', 'mumble', 255)
(0, '', '', 0)

HTH,
John




More information about the Python-list mailing list