On Tue, Sep 7, 2010 at 9:53 PM, Eli Bendersky <eli...@gmail.com> wrote: >> >> I'm trying to rewrite a c program in python & encountered several >> problems. I have some data structures in my c program like below: >> >> typedef struct >> { >> unsigned short size; >> >> unsigned short reserved:8; >> unsigned short var_a1:2; >> unsigned short var_a2:2; >> unsigned short var_a3:2; >> unsigned short var_a4:2; >> >> unsigned int var_a5; >> }structa; >> >> typedef struct >> { >> unsigned short size; >> >> unsigned char reserved:4; >> unsigned char var_b1:1; >> unsigned char var_b2:1; >> unsigned char var_b3:1; >> unsigned char var_b4:1; >> >> structa var_structa; >> }structb; >> >> I tried to code the above in python but only got this far: >> >> class StructA(object): >> def __init__(self, size=0) >> self.size = size >> >> class StructB(object): >> def __init__(self, size=0) >> >> Any equivalent for c data structures & bit fields in python? And how do I >> define var_structa (in structb) in python? >> > > Bitfields are most commonly used for extreme space optimization - i.e. > shoving several variables and flags with carefully limited ranges into a > single work. In Python you rarely work this way (where such an optimization > is warranted, Python isn't the best tool for the job). However, as in your > use case, it is sometimes needed in Python in order to communicate with > other devices over the network or some other link. > > In my work with Python and embedded devices I've found the construct library > (http://construct.wikispaces.com/) very useful. It allows to you very easily > define complex formats for frames/messages on the bit and byte level. The > idea is to use construct to encode and decode messages being sent to an > embedded device. It works great. > > If you have further questions about this approach, feel free to ask. > > Eli
That's really an excellent find. Thanks for bringing it up. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list