Is there a straightforward way to extracting the exponent from a power of 2 using bitwise operations only?
EDIT: Although the question was originall
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.