iterating bit-by-bit across int?

Skip Montanaro skip at pobox.com
Thu Oct 23 15:24:05 EDT 2003


    Matthew> I'm playing around with genetic algorithms and I want to write
    Matthew> a function that mutates an integer by iterating across the
    Matthew> bits, and about 1 in 10 times, it should switch a zero to a
    Matthew> one, or a one to a zero.

Just use Python's bitwise ops, for example:

    >>> x = 0x0FFFCCCC 
    >>> hex(x)
    '0xfffcccc'
    >>> hex(x | (1 << 13))
    '0xfffeccc'

Skip





More information about the Python-list mailing list