_DeBruijnBitPosition = [
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
]
def _trunc32( w ):
w = int( ( w & 0x7fffFFFF ) | -( w & 0x80000000 ) )
return w
def findSetBits(v):
while v:
index = _DeBruijnBitPosition[_trunc32((v & -v) * 0x077CB531) >> 27]
v = (v & v-1)
yield index
# usage: list(findSetBits(4937)) => [0, 3, 6, 8, 9, 12]
I don't happen to have a native python interpreter handy - fancy benchmarking this against your earlier list comprehension solution?