Pythonic way to iterate over bits of integer

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

    S.O. won't let me put this as a comment, but here's a line-by-line example of how Duncan's solution works. Hopefully this clarifies what's happening.

    Let's use the decimal number 109 as an example:

    # 109 is .............. 0110 1101
    # ~109 is -110 which is 1001 0010   NOTE: It's -110 instead of -109 because of 1's compliment
    # ~109+1 is -109....... 1001 0011
    # 109 AND ~109 is...... 0000 0001 = 1  <---- 1st value yielded by the generator
    # 109 XOR 1 is......... 0110 1100 = n = 108
    
    # 108.................. 0110 1100
    # ~108+1= -108......... 1001 0100
    # 108 AND -108......... 0000 0100 = 4  <---- 2nd value yielded by the generator
    # 108 XOR 4............ 0110 1000 = n = 104
    
    # 104.................. 0110 1000
    # ~104+1............... 1001 1000
    # 104 AND -104......... 0000 1000 = 8  <---- 3rd value yielded by the generator
    # 104 XOR 8............ 0110 0000 = n = 96
    
    # 96................... 0110 0000
    # ~96+1................ 1010 0000
    # 96 AND -96........... 0010 0000 = 32 <---- 4th value yielded by the generator
    # 96 XOR 32............ 0100 0000 = n = 64
    
    # 64................... 0100 0000
    # ~64+1................ 1100 0000
    # 64 AND -64........... 0100 0000 = 64 <---- 5th value yielded by the generator
    # 64 XOR 64............ 0000 0000 = n = 0; thus, the while loop terminates.
    

提交回复
热议问题