Pythonic way to iterate over bits of integer

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

    Example one-line solution:

    [1 << bit for bit in xrange(bitfield.bit_length()) if bitfield & (1 << bit)]
    

    Or:

    [bit for bit in (1 << n for n in xrange(bitfield.bit_length())) if bitfield & bit]
    

    Notes:

    • use range in Python 3
    • think about checking bitfield is >= 0

提交回复
热议问题