Pythonic way to iterate over bits of integer

前端 未结 7 2081
面向向阳花
面向向阳花 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

    Python 2.7:

    def binary_decomposition(x):
        p = 2 ** (int(x).bit_length() - 1)
        while p:
            if p & x:
                yield p
            p //= 2
    

    Example:

    >>> list(binary_decomposition(109))
    [64, 32, 8, 4, 1]
    

提交回复
热议问题