pack/unpack zero terminated string

tmp123 tmp123 at menta.net
Thu May 3 03:28:03 EDT 2007


On May 2, 11:13 pm, John Machin <sjmac... at lexicon.net> wrote:
> On May 3, 12:01 am, Laurent Pointal <laurent.poin... at limsi.fr> wrote:
>
>
>
>
>
>
>
> >tmp123a é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

Hello John,

Totally true, the solution you propose is the one I'm using now. The
subject was, before to start from scratch, try to reuse something
existing.

Another possibility was to modify the "struct" package with the new
option, but it seems a mixed C-Python implementation, and I do not
like to start having compatibility problems in the C elements.

Kind regards.




More information about the Python-list mailing list