iterating bit-by-bit across int?

Andrew Dalke adalke at mindspring.com
Thu Oct 23 17:03:32 EDT 2003


Matthew Wilson:
> I'm not sure how many bits are inside a python integer.  The library
> reference says at least 32.

Platform dependent.  Could be 64 on 64 bit machines.

> I'm thinking about writing a function that eats integers and poops out
> lists of bools; and then I can iterate through that, and change values
> in there.  But before I do that, does anyone have a better idea?

Python isn't good for that sort of low-level bit twiddling.

Here's another possibility.  Use a long int as your genome,
then make a new long int which describes the bits which
need to be inverted, then apply an xor between them.

import random

def toLSBBinary(x, num_bits):
    letters = []
    for i in range(num_bits):
        if x & (1L << i):
            letters.append("1")
        else:
            letters.append("0")
    return "".join(letters)

genome = 3454579853467L
num_bits = 42

bitmask = 0
for i in range(num_bits):
    if random.random() < 0.1:
        bitmask += 1L<<i

# genome bit, bitmask -> new value for genome
#  if the bitmask is 0, don't change anything
#  if it is 1, invert the value
# 0 0 -> 0
# 1 0 -> 1
# 0 1 -> 1
# 1 1 -> 0
#  This is an xor
new_genome = (genome ^ bitmask)

print toLSBBinary(genome, num_bits)
print toLSBBinary(bitmask, num_bits)
print toLSBBinary(new_genome, num_bits)


Here's the output of the above

110110010001001010000000101010100010010011
100000101110100000000000000000000000010000
010110111111101010000000101010100010000011

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list