Efficient Bit addressing in Python.

Aaron "Castironpi" Brady castironpi at gmail.com
Fri Oct 10 23:37:58 EDT 2008


On Oct 9, 5:30 pm, "Hendrik van Rooyen" <m... at microcorp.co.za> 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

This is tolerable.  If you've got a better 'clear' operation than
'xor', you're welcome to it.

class BitSet:
    def __init__( self, value ):
        self.value= value
    def __setitem__( self, index, value ):
        if value:
            self.value= self.value| (1<< index)
        elif self[ index ]:
            self.value= self.value^ (1<< index)
    def __getitem__( self, index ):
        return self.value& (1<< index )
    def __repr__( self ):
        return repr( self.value )

if __name__== '__main__':
    b= BitSet( 15 )
    print b
    b[0]= 0
    print b
    b[0]= 1
    print b
    b[4]= 1
    print b
    b[4]= 0
    print b

/Output:
15
14
15
31
15



More information about the Python-list mailing list