Efficient Bit addressing in Python.
Aaron "Castironpi" Brady
castironpi at gmail.com
Fri Oct 10 23:41:08 EDT 2008
On Oct 10, 10:37 pm, "Aaron \"Castironpi\" Brady"
<castiro... at gmail.com> wrote:
> 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?
snip
>
> 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 )
snip
This could read:
def __getitem__( self, index ):
return 1 if self.value& (1<< index ) else 0
Or you could shift self.value, and mask with unity.
More information about the Python-list
mailing list