Bit Arrays

Charles G Waldman cgw at fnal.gov
Tue Apr 20 15:06:36 EDT 1999


Laura Paterno writes:
 > Hello all,
 > 
 > I want to write a python program that has 26 Bit Arrays that each contain
 > 1113 bits. Is there a structure in python that one can use to represent a
 > bit array?
 > 

Hi Laura.  

If memory efficiency is not an issue you could just use a string (or
list of strings).  If you really need to pack bits, then this takes a
bit more work.  You could use an array object (either from the
built-in array class or the fancy Array object from the Numeric
extension) and do the bit-slicing yourself in Python, something like
this (you could put in more type-checking, etc.)

import array
import exceptions

class MyObject:
      def __init__(self):
	  self.data = []
	  for i in range(26):
	      self.data.append(array.array(140,'b'))

      def __setitem__(self, key, value):
	  if len(key)!=2:
	     raise exceptions.ValueError, "expected two indices"
	  if value not in (0,1):
	     raise exceptions.ValueError, "value must be 0 or 1"
	  if key[0]>25 or key[0]<0:
	     raise exceptions.ValueError, "index out of range"%key[0]
	  if key[1]>139 or key[1]<0:
	     raise exceptions.ValueError, "index out of range"
	  arr = self.data[key[0]]
	  offset, bit = divmod(key[1],8)
	  arr[offset] = arr[offset] | 1<<bit

      def __getitem__(self, key):
	  if len(key)!=2:
	     raise exceptions.ValueError, "expected two indices"
	  arr = self.data[key[0]]
	  offset, bit = divmod(key[1],8)
	  if arr[offset] & 1<<bit:
	       return 1
	  return 0


This will be memory-efficient but somewhat slow.  If you need
memory-efficiency *and* speed then you could define your structure in
C/C++ and use SWIG to generate a "shadow class".




More information about the Python-list mailing list