Efficient Bit addressing in Python.

Hendrik van Rooyen mail at microcorp.co.za
Thu Oct 9 18:30:18 EDT 2008


Is there a canonical way to address the bits in a structure
like an array or string or struct?

Or alternatively, is there a good way to combine eight
ints that represent bits into one of the bytes in some
array or string or whatever?

It seems to me that there is a dilemma here :

if you can write:

bit3 = 1

Then you have to jump through hoops to get
bit0 through bit7 into some byte that you can send
to an i/o routine.

On the other hand, if you keep the bits "in" the 
byte, then you can write:

byte[3] = '\x7e'

but you have to jump through hoops to get at 
the individual bits.

Is there a "best" way?

It would be nice to be able to write:

if io.byte2.bit3:
   do_something()

if io.byte2 == alarm_value:
  do_something_else()

where:

 io.byte2 & 8   "is"  io.byte2.bit3

Is this possible?

- Hendrik




More information about the Python-list mailing list