views:

243

answers:

4

In an assignment I am currently working on we need to work with bit vectors, but I am very unsure of how to do this in Python. They should be able to be from 4 bits to 20 bits. I have never worked with bit vector before, but I guess that one would one create arrays of unsigned bytes that you manipulated using the usual AND/OR/XOR operations.

The important restriction here is: I cannot rely on any libraries other than those supplied with standard Python.

I think I know how I would do this in C using arrays of 8 bit unsigned bytes: e.g. to turn the 18th bit of a zeroed array into a one, I would do something like my_bit_array[3] &= 1<<2

But since Python is dynamically typed and does not have a built-in array type, how would I go about doing this in a pythonic way?

And is it possible (how?) to express a bit vector of size 20? I am thinking of perhaps making a 24 bit / 3 byte vector and ignoring the 4 bits.

+3  A: 

It has lists, which you can populate with bools:

[False] * 20
Ignacio Vazquez-Abrams
Would this occupy 20 bytes or 20 bits of memory? I need to use *lots* of these
It would occupy 20+1 pointers. True and False are singletons.
Ignacio Vazquez-Abrams
Thanks for the input! I guess I will have to go with the structs module in that case.
A: 

Use struct module.

gruszczy
Could you give me an example of creating a 3 byte array and setting a bit? I do not know the basic binary operators in Python.
I used it only once, when I needed to write some low level stuff. The docs are very fine, though.
gruszczy
+1  A: 

The library BitVector is a pure-Python library for this purpose, and should suit the needs you specified.

Håvard S
Good library. Didn't use it, but learned a lot from reading the code. Turns out that in the nitty-gritty details the author of BitVector is using an array of (8 bit) bytes, just like I was pondering.
+4  A: 

The bitarray module does this efficiently with booleans.

ezod