iterating bit-by-bit across int?
Brian Kelley
bkelley at wi.mit.edu
Thu Oct 23 16:07:32 EDT 2003
Paul Rubin wrote:
> Matthew Wilson <mwilson at sarcastic-horse.com> writes:
>
>>I'm playing around with genetic algorithms and I want to write a
>>function that mutates an integer by iterating across the bits, and about
>>1 in 10 times, it should switch a zero to a one, or a one to a zero.
>>
>>I'm not sure how many bits are inside a python integer. The library
>>reference says at least 32.
>
>
> Long ints can have as many bits as you want.
Such as -1L which has an infinite number of bits.
I have used a list of integers as my defacto standard for representing a
stream of bits. On my windows box this is slower than using a long
integer but with psyco running (psyco.sourceforge.net) it is faster than
the long integer implementation.
It also is faster to bail out on a comparison, for example
if (a&b)!= 0:
can be optimized to fail on the first integer failure, it doesn't have
to complete the operation as it would with a long integer.
This is useful when seeing if a bit string is contained inside another
bit string.
More information about the Python-list
mailing list