Pythonic way to iterate over bits of integer

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

    The efficiency of F.J.'s answer can be dramatically improved.

    from itertools import count,takewhile
    [2**i for i in takewhile(lambda x:109>2**x,count()) if 109&2**i][::-1]
    

    I like one liners :)

    I did a quick timeit.Timer.timeit() against this and @Duncan. Duncan still wins but not the one liner is at least in the same class.

    from timeit import Timer
    duncan="""\
    def bits(n):
     while n:
      b=n&(~n+1)
      yield b
      n^=b
    """
    Duncan=Timer('list(bits(109))[::-1]',duncan)
    Duncan.timeit()
    4.3226630687713623
    freegnu=Timer('[2**i for i in takewhile(lambda x:109>2**x,count()) if 109&2**i][::-1]','from itertools import count,takewhile')
    freegnu.timeit()
    5.2898638248443604
    

提交回复
热议问题