Bitsets in Python

Josiah Carlson jcarlson at nospam.uci.edu
Thu Feb 5 10:39:53 EST 2004


> BitSets crop up in (at least) C++ and Java. They allow you operate on
> a sequence of bits using a friendlier interface than hacking about
> with ^,|,& et al on integers. The Java BitSet interface:

I would suggest subclassing int:

class bitset(int):
     def __getitem__(self, k):
         return (2**k & self) >> k
     def __setitem__(self, k, v):
         #this doesn't work
         if v:
             return bitset(2**k | self)
         elif self[k]:
             return bitset(2**k ^ self)

Unfortunately, due to the semantics of item setting a[i] = j, you cannot 
return anything from a setitem, and integers are immutable, so you 
cannot modify bitset directly.

Sounds like something in need of a custom class.  Thankfully it wouldn't 
be too difficult.

  - Josiah



More information about the Python-list mailing list