Efficient Bit addressing in Python.

Lie Ryan lie.1296 at gmail.com
Thu Oct 9 11:22:53 EDT 2008


On Fri, 10 Oct 2008 00:30:18 +0200, Hendrik van Rooyen wrote:

> 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

You'll find that in most cases, using integer or Boolean is enough. There 
are some edge cases, which requires bit addressing for speed or memory 
optimizations, in python, the usual response to that kind of optimization 
requirement is to move that part of the code to C.

If, for the more usual case, you require the bit addressing because the 
data structure is more convenient to work with that way, you could use a 
class that implements the __getitem__, __setitem__, and a "join" method.

anyway, if you used str, it isn't hard to have both behavior (easy 
indexing and easy joining) the bits:
>>> a = '01101010'
>>> a[0], a[1]
('0', '1')
>>> a
'01101010'
>>> int(a, 2)
106
>>> chr(int(a, 2))
'j'
>>> def bin2int(b): return int(a, 2)
...
>>> def bin2chr(b): return chr(int(a, 2))
...
>>>




More information about the Python-list mailing list