Creating a Bitarray in python

Sunday, July 1, 2012

This code shows an implementation of bitarray in python using the bytearray built-in function, it can set/unset and fetch a bit from a given array index location, in the below example we create a bitarray of size 32k.

Listing 1: bitarray.py

"""
   Creating and accessing elements in a bitarray
   The bitarray is created from a bytearray
   
   Author: S.Prasanna
"""

class Bitarray:
    def __init__(self, size):
        """ Create a bit array of a specific size """
        self.size = size
        self.bitarray = bytearray(size/8)

    def set(self, n):
        """ Sets the nth element of the bitarray """

        index = n / 8
        position = n % 8
        self.bitarray[index] = self.bitarray[index] | 1 << (7 - position)

    def get(self, n):
        """ Gets the nth element of the bitarray """
        
        index = n / 8
        position = n % 8
        return (self.bitarray[index] & (1 << (7 - position))) > 0 

    def unset(self, n):
        """ Unsets the nth element of the bitarray """
        
        index = n / 8
        position = n % 8
        self.bitarray[index] = self.bitarray[index] & ((1 << (7 - position)) - 1)

if __name__ == "__main__":
    bitarray_obj = Bitarray(32000)
    for i in range(5):
        print "Setting index %d of bitarray .." % i
        bitarray_obj.set(i)
        print "bitarray[%d] = %d" % (i, bitarray_obj.get(i))
        print "Unset index %d of bitarray .." % i
        bitarray_obj.unset(i)
        print "bitarray[%d] = %d" % (i, bitarray_obj.get(i))
Syntax highlighter: Pygments

Sample Output:

>>>
Setting index 0 of bitarray ..
bitarray[0] = 1
Unset index 0 of bitarray ..
bitarray[0] = 0
Setting index 1 of bitarray ..
bitarray[1] = 1
Unset index 1 of bitarray ..
bitarray[1] = 0
Setting index 2 of bitarray ..
bitarray[2] = 1
Unset index 2 of bitarray ..
bitarray[2] = 0
Setting index 3 of bitarray ..
bitarray[3] = 1
Unset index 3 of bitarray ..
bitarray[3] = 0
Setting index 4 of bitarray ..
bitarray[4] = 1
Unset index 4 of bitarray ..
bitarray[4] = 0
>>>


Copyright © 2008 Prasanna Seshadri, www.prasannatech.net, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.