Bit fields in python?

Eli Bendersky eliben at gmail.com
Wed Sep 15 07:31:31 CEST 2010


>  Hi,
>
> I'm trying to use the construct library, but encountered a problem. May I
> know how do I implement the following using the construct library?
>
> typedef struct
> {
>     unsigned short size;
>     .
>     .
> }CodecInfo;
>
> typedef struct
> {
>     unsigned short size;
>     CodecInfo mastercodec;
>     CodecInfo slavecodec;
> }StatusInfo;
>
> StatusInfo t;
> printf("%hu %hu\n", t.mastercodec.size,t.slavecodec.size);
>
> Not sure how to include 2 copies of the CodecInfo Struct into StatusInfo
> Struct & be able to access CodecInfo's fields like the example above:
>
> CodecInfo = Struct("CodecInfo",
>                     .
>                     .
>                     .
> )
>
> StatusInfo = Struct("StatusInfo",
>                 CodecInfo,
>                 CodecInfo
> )
>
> Status = StatusInfo.parse(buf)
>
>
You can just nest Struct objects. Here's one implementation of what you're
looking for:

from construct import *

def make_codec_info(name):
    return Struct(name,  ULInt16('size'))

StatusInfo = Struct('StatusInfo',
                        ULInt16('size'),
                        make_codec_info('mastercodec'),
                        make_codec_info('slavecodec'),
                        )

c = StatusInfo.parse('\x12\x13\x01\x02\x03\x04')

print c

P.S. It is covered in the first part of construct's tutorial (
http://construct.wikispaces.com/tut-basics). The tutorial is a pretty good
starting point for using construct.

Eli
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100915/d9e98941/attachment.html>


More information about the Python-list mailing list