Finding the exponent of n = 2**x using bitwise operations [logarithm in base 2 of n]

后端 未结 7 1107
猫巷女王i
猫巷女王i 2020-12-31 05:47

Is there a straightforward way to extracting the exponent from a power of 2 using bitwise operations only?

EDIT: Although the question was originall

7条回答
  •  心在旅途
    2020-12-31 06:12

    You can do it in O(lg s) time for arbitrary length integers using a binsearch.

    import sys
    def floorlg(n):
        if n < 1:
            return -1
        low=0
        high=sys.getsizeof(n)*8 # not the best upper-bound guesstimate, but...
        while True:
            mid = (low+high)//2
            i = n >> mid
            if i == 1:
                return mid
            if i == 0:
                high = mid-1
            else:
                low = mid+1
    

    For fixed size integers, a lookup table should be the fastest solution, and probably best overall.

提交回复
热议问题