iterating bit-by-bit across int?
Paul Watson
pwatson at redlinec.com
Thu Oct 23 23:22:54 EDT 2003
"Diez B. Roggisch" <deets_noospaam at web.de> wrote in message
news:bn9acd$4s6$06$1 at news.t-online.com...
> > 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?
>
> For speed, you should use shift and boolean ops - like this:
>
> def mutate(seq, n=32, prob=0.05):
> for bit in xrange(n):
> if random.random() <= prob:
> seq ^= 1 << bit
> return seq
>
> Regards,
>
> Diez
And you might want to make a list of precalculated masks using the shift
operator for even more speed.
#! /usr/bin/env python
import sys
print sys.maxint
i = sys.maxint
bitcount = 0
while (i != 0):
i >>= 1
bitcount += 1
print "i = %d" % (i)
print "bitcount = %d" % (bitcount)
masklist = []
for i in range(bitcount):
masklist.append(1 << i)
masklist.append(sys.maxint + 1)
for i in masklist:
print hex(i)
thelist = [0x7F, 0x5A5A5A5A]
for i in thelist:
for mask in masklist:
if ((i & mask) <> 0):
# do True thing
print "True"
else:
# do False thing
print "False"
More information about the Python-list
mailing list