迭代整数位的Python方法 [英] Pythonic way to iterate over bits of integer
本文介绍了迭代整数位的Python方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以二进制形式的a=109
或1101101
.我如何遍历此数字的位,例如:[64, 32, 8, 4, 1]
Let's a=109
or 1101101
in binary. How do I iterate over bits of this number, eg: [64, 32, 8, 4, 1]
推荐答案
有一个技巧,可以从二进制表示形式中取出1,而不必遍历所有中间的0:
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
这篇关于迭代整数位的Python方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文