Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

bit manipulation - Python - Fastest way to calculate log2(int) of a number that is an integral power of 2

I'm using bitsets and want to iterate over the set bits quickly, and without needing to know the max set bit ahead of time. Using this trick, it seems like we can do this without scanning the 0s in the middle. But the linked trick produces set bits as bitsets, not as integers (e.g. the 0th set bit is produced as 0b1, not 0).

Is there a fast bit trick to calculate log2(x) when I know x will be an exact power of 2 (e.g. as in the above case)?

What have I tried

Simplest version, using the standard library and with bits(n) being the linked code:

def bits(n):
    while n:
        b = n & (~n+1)
        yield b
        n ^= b

from math import log2
   
for b in bits(109):
    print(int(log2(b)))

0
2
3
5
6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try:

log2 = b.bit_length() - 1

- 1 because 2? requires n+1 bits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...