Pythonic way to iterate over bits of integer

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

    My approach:

    def bits(number):
        bit = 1
        while number >= bit:
           if number & bit:
               yield bit
           bit <<= 1
    

    I don't think there is a builtin function for it.

    I also wonder if there isn't a better approach to whatever you are doing. There's a good chance you don't really want to iterate over the bits like this. They may be a much better way.

    Out of curiosity I ran some timing on the methods posted here, my results:

    Winston 2.35238099098
    F.J. 6.21106815338
    F.J. (2) 5.21456193924
    Sven 2.90593099594
    Duncan 2.33568000793
    freegnu 4.67035484314
    

    F.J. converts to a string, I'm guessing that hurts his performance. The various optimisation attempts help, but not enough Sven produces the reverse of everybody else, which might be an advantage if you really needed that. Duncan's approach wins speedwise (just barely)

    Again with 340282366920938463463374607431768211457 instead of 109:

    Winston 44.5073108673
    F.J. 74.7332041264
    Sven 47.6416211128
    Duncan 2.58612513542
    

    Nice, Duncan! It should be noted that this is pretty much the best case for Duncan's method, so it won't always have this dramatic an advantage.

    0 讨论(0)
提交回复
热议问题