[Tutor] working with bit arrays

Alan Plum alan.plum at uni-koeln.de
Wed Dec 2 23:32:39 CET 2009

On Mi, 2009-12-02 at 13:08 -0500, Robert Berman wrote:
> Hi,
> I am trying to represent a number as a list of bits: for example the
> bit representation of the integer 8. I did find a number of articles
> pertaining to a module called bitarray but I was unable to
> download/install that package. I am using Linux on Ubuntu 9.10; Python
> 2.6.2. 
> I am almost certain there is a relatively easy way to convert an
> integer that can be represented by 32 bits into an array of bits that
> I can iterate over looking for switched on bits or switched off bits. 

If all you want is to treat integers as lists of bits, you could create
a wrapper class around an integer and implement the __getitem__ and
__setitem__ methods to make it behave like a list. Using the bitwise
operators, you could make the setter actually modify the bit in question
(you'd probably have to either make sure you only receive 1 or 0 as
value or you could simply use booleans instead).

For a challenge you could try to extend the built-in integer type this

I'm not sure why you'd need to be able to address bits directly like
that, though. Normally the bitwise &, |, << and >> should suffice for
all intents and purposes.

Making an ACTUAL lists of ACTUAL integers representing the bits would be
overkill, though. We're talking several bytes worth of nulls to
represent a single bit. I'm all for late optimisation, but this just
doesn't feel right.



More information about the Tutor mailing list