Pythonic way to iterate over bits of integer

前端 未结 7 2295
面向向阳花
面向向阳花 2021-02-02 08:08

Let\'s a=109 or 1101101 in binary. How do I iterate over bits of this number, eg: [64, 32, 8, 4, 1]

7条回答
  •  我在风中等你
    2021-02-02 08:49

    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
    

提交回复
热议问题