Efficient Bit addressing in Python.

Hendrik van Rooyen mail at microcorp.co.za
Fri Oct 10 17:29:19 EDT 2008


Lie Ryan wrote:


>You'll find that in most cases, using integer or Boolean is enough. There
>are some edge cases, which requires bit addressing for speed or memory
>optimizations, in python, the usual response to that kind of optimization
>requirement is to move that part of the code to C.
>
>If, for the more usual case, you require the bit addressing because the
>data structure is more convenient to work with that way, you could use a
>class that implements the __getitem__, __setitem__, and a "join" method.

I had a vague feeling that this was the way to go,(see
my reply to Tino) but I have been resisting, kicking
and screaming, to get deeply involved in OO - Using
Tkinter is enough OO for my microprocessor biased
taste.

>anyway, if you used str, it isn't hard to have both behavior (easy
>indexing and easy joining) the bits:
>
>>>> a =3D '01101010'
>>>> a[0], a[1]
>('0', '1')
>>>> a
>'01101010'
>>>> int(a, 2)
>106
>>>> chr(int(a, 2))
>'j'
>>>> def bin2int(b): return int(a, 2)
...
>>>> def bin2chr(b): return chr(int(a, 2))

Thanks. This is the best I have seen up to now.

I was stuck because I was insisting on
storing real bits in real strings, eight
bits per byte, instead of storing ascii bits
and remembering about int(x,2).

In fact I keep forgetting about the
second argument of int...

I could go with a list like this:

inputs = [['10001000',''],['11110000',''],['01010101','']]

Where the second entry in the list is a "changed" bit.

Outputs are a bit more of a hassle - strings are immutable,
so I can't  write:

input[1][0][3]='1'

but that is easily fixed by using array.array.

Thanks for the response

- Hendrik






More information about the Python-list mailing list