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

Categories

0 votes
3.7k 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 Reply

0 votes
by (71.8m points)

Try:

log2 = b.bit_length() - 1

- 1 because 2? requires n+1 bits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...