Efficient Bit addressing in Python.

Hendrik van Rooyen mail at microcorp.co.za
Sun Oct 12 05:58:47 CEST 2008


"Aaron \"Castironpi\" Brady" wrote:

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

*grin* xor is a toggle bit fuction, and I did not like the recursive
call in your code. so here is a module bsed on your BitSet:
(I hope my tabs survive the journey)


"""
Module with input and output int bit addressable classes.

Loosely based on Castironpi's BitSet code

"""

class inbits(object):
 """
 This is a 32 bit int of more or less addressable bits.
 """

 def __init__ (self, value = 0,*args ):
  """This constructs the int that keeps the bits,
     and makes a getbit function for each named bit from *args,
     so that we can retreive them by instance.bitname(),
     as well as by bool = instance[index_position]
  """

  self.value = value
  self.high_values = int('ffffffff',16)
  for i,name in enumerate(args):
   def __getbit__(idx = i):
# Real i/o code has to be added here to read the right byte
    return self.__getitem__(idx)
   self.__dict__[name] = __getbit__

 def __setitem__( self, index, value ):
  """Here we can set a bit based on its position."""

  if value:
   self.value |= (1 << index)
  else:
   self.value &= self.high_values ^ (1 << index)

 def __getitem__( self, index ):
  """This retreives a bit based on its position."""

  return 1 if self.value & (1<< index ) else 0

 def __repr__( self ):
  return repr( self.value )



class outbits(object):
 """
 This is a 32 bit int of more or less addressable bits.
 """

 def __init__ (self, value = 0,*args ):
  """This constructs the int that keeps the bits,
     and makes a setbit function for each named bit from *args,
     so that we can set them by instance.bitname(bool),
     as well as by instance[index_position] = bool
  """

  self.value = value
  self.high_values = int('ffffffff',16)
  for i,name in enumerate(args):
   def __setbit__(value,idx = i):
    self.__setitem__(idx,value)
# Real i/o code has to be added here to write the right byte out
   self.__dict__[name] = __setbit__

 def __setitem__( self, index, value ):
  """Here we can set a bit based on its position."""

  if value:
   self.value |= (1 << index)
  else:
   self.value &= self.high_values ^ (1 << index)

 def __getitem__( self, index ):
  """This retreives a bit based on its position."""

  return 1 if self.value & (1<< index ) else 0

 def __repr__( self ):
  return repr( self.value )



if __name__== '__main__':

 ins  = inbits(0,'b0','b1','b2','b3','b4','b5','b6','b7')
 outs = outbits(0,'b0','b1','b2','b3','b4','b5','b6','b7')
 ins[3] = 1
 outs.b4(1)
 print 'ins now',ins,'outs now',outs,'outs[4] is',outs[4],'ins.b3() is',ins.b3()


Comments are welcome...

- Hendrik







More information about the Python-list mailing list