Pythonic way to iterate over bits of integer
问题 Let's a=109 or 1101101 in binary. How do I iterate over bits of this number, eg: [64, 32, 8, 4, 1] 回答1: There's a trick for just getting the 1's out of the binary representation without having to iterate over all the intervening 0's: def bits(n): while n: b = n & (~n+1) yield b n ^= b >>> for b in bits(109): print(b) 1 4 8 32 64 回答2: My approach: def bits(number): bit = 1 while number >= bit: if number & bit: yield bit bit <<= 1 I don't think there is a builtin function for it. I also wonder