this is an option (you are looking for the log
arithm in base 2):
from math import log2
def integer_log2(n):
if not bin(n).count("1") == 1:
raise ValueError
return int(log2(n))
in binary representation (bin(n)
) a number an only be an integer power o 2 it it contains exactly one 1
. the function presented here will raise a ValueError
if this is not the case.
integer_log2(64))
# 6
as you'd need the binary representation anyway, you could then also just count the number of 0
s to get the log:
def integer_log2(n):
b = bin(n)
if not b.count("1") == 1:
raise ValueError
return b.count("0") - 1