Bit fields in python?

Terry Reedy tjreedy at udel.edu
Tue Sep 7 14:28:38 EDT 2010


On 9/7/2010 12:06 AM, Kwan Lai Cheng wrote:
> Hi,
> 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;

In Python, we cannot directly name bitfields within an int. However, we can
*read, set, and flip bits with the bit operators and bit masks
*define a dict that maps bitfield names to bit indexes
*define named functions that use the above.
*wrap or subclass int with a class that has attributes that map to a 
bitfield.

I am pretty sure there is public code that does all of the above. 
Searching pypi.python.org for 'bitfield', I found

BitDecoder 0.5.1

Decode bit-fields to human readable description

This program (and Python module) will decode a value as per a bitfield 
definition. This is very useful for hardware registers that have 
meanings to parts of the bits in seperate.

Google for more.

-- 
Terry Jan Reedy




More information about the Python-list mailing list