Want to build a binary header block

Nick Craig-Wood nick at craig-wood.com
Wed May 2 05:30:04 EDT 2007


Bob Greschke <bob at greschke.com> wrote:
>  This is the idea
> 
>     Block = pack("240s", "")
>     Block[0:4] = pack(">H", W)
>     Block[4:8] = pack(">H", X)
>     Block[8:12] = pack(">B", Y)
>     Block[12:16] = pack(">H", Z))
> 
>  but, of course, Block, a str, can't be sliced.

You could do this (note anonymous mappings require python 2.5)

    >>> from mmap import mmap
    >>> from struct import pack
    >>> W,X,Y,Z=1,2,3,4
    >>> Block = mmap(-1, 1024)
    >>> Block[0:2] = pack(">H", W)
    >>> Block[4:6] = pack(">H", X)
    >>> Block[8:9] = pack(">B", Y)
    >>> Block[12:14] = pack(">H", Z)
    >>> Block[0:16]
    '\x00\x01\x00\x00\x00\x02\x00\x00\x03\x00\x00\x00\x00\x04\x00\x00'
    >>>

You might also want to consider Construct

  http://construct.wikispaces.com/

>From the web page: Construct is a python library for parsing and
building of data structures (binary or textual). It is based on the
concept of defining data structures in a declarative manner, rather
than procedural code: more complex constructs are composed of a
hierarchy of simpler ones. It's the first library that makes parsing
fun, instead of the usual headache it is today.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list