iterating bit-by-bit across int?
Jan Decaluwe
jan at jandecaluwe.com
Fri Oct 24 04:42:55 EDT 2003
Matthew Wilson wrote:
> 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.
>
> 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?
You may be interested in the 'intbv' class that is part of my 'myhdl'
package for hardware design (link: see signature).
An intbv behaves like a Python long with an indefinite number of bits.
However, it is a mutable type that can also be used as a bitvector
through an indexing and slicing interface. Warning: slicing ranges are
downward as is common in hardware design but uncommon in Python.
Demo:
>>> from myhdl import intbv
>>> n = intbv(0xDE)
>>> n[:8] = 0xFA
>>> hex(n)
'0xFADEL'
>>> n[8:] = 0xB4
>>> hex(n)
'0xFAB4L'
>>> for bit in n[12:8]:
... print bit
...
1
0
1
0
>>> n[123]
intbv(0L)
>>> n[123] = 1
>>> hex(n)
'0x800000000000000000000000000FAB4L'
Regards, Jan
--
Jan Decaluwe - Resources bvba - http://jandecaluwe.com
Losbergenlaan 16, B-3010 Leuven, Belgium
Bored with EDA the way it is? Check this:
http://jandecaluwe.com/Tools/MyHDL/Overview.html
More information about the Python-list
mailing list