[Tutor] working with bit arrays

GilJohnson x7-g5W_rt at earthlink.net
Thu Dec 3 01:10:26 CET 2009


As`Kent Johnson pointed out, you don't need to convert anything to strings, etc.
An integer _is_ a bit array, and individual bits can be tested using the bitwise
operators. For your example, if A is an integer you can test bit 8 with:
if A & (1 << 8): dosomething
There is a simple example on the Python wiki at
http://wiki.python.org/moin/BitArrays
It uses an array of 32-bit integers as a bit array.
The advantage of using 'bitarray' or one of the other packages on the Python
Package Index is that they have implemented all of the slicing, etc. of Python
lists, strings, etc. Using an array of 32 bit integers, you have to go to some
trouble to slice out, say, bits 20 to 40.
HTH,
Gil




More information about the Tutor mailing list