[Tutor] working with bit arrays

Chris Fuller cfuller084 at thinkingplanet.net
Wed Dec 2 19:51:29 CET 2009


My approach has been to store it as an array and then build the integer as 
needed.  This code requires Python 2.5 or later.

def bits2int(l):
   return sum([2**i if j else 0 for i,j in enumerate(l)])

To convert the other way:

def int2bits(m, n):
   return [int(bool(m&(1<<i))) for i in range(n)]

Where n is the number of bits to convert.  You could log2 to find this, or 
count shift-rights until you get zero.

# for example, inc=4 gives log16, or the number of hexadecimal digits
# required to represent n.
def log2(n, inc=1):
   i = 0
   while n:
      i += 1
      n >>= inc

   return i

floating point is so messy and slow :)

Cheers

On Wednesday 02 December 2009 12:08, 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.
>
> Any information such as recipes or past articles in this list providing
> methods to create and manipulate  bit arrays would be most appreciated.
>
> Robert


More information about the Tutor mailing list