Let\'s a=109
or 1101101
in binary. How do I iterate over bits of this number, eg: [64, 32, 8, 4, 1]
>>> [2**i for i, v in enumerate(bin(109)[:1:-1]) if int(v)]
[1, 4, 8, 32, 64]
Obviously the order is reversed here, you could either just use this or reverse the result:
>>> [2**i for i, v in enumerate(bin(109)[:1:-1]) if int(v)][::-1]
[64, 32, 8, 4, 1]
edit: Here is a slightly longer version that should be more efficient:
from itertools import takewhile, count
[p for p in takewhile(lambda x: x <= 109, (2**i for i in count())) if p & 109]