Search code examples
pythonmathematical-optimization

How to take inverse of 2 raise to something in python2.5 (strict)


I have a number say 37. 37 lies between 2**5 and 2**6. I want to write a function which takes the number as argument and returns the power of its lower bounderies.

def foo(x=37)
{
 result =//Here calculation
 return result
}

In the above example the return should be 5 because its lower limit is 2**5 and 5 is its power.

Note: Must be care about python 2.5

Thanks in advance.


Solution

  • import math
    def hi_bit(num):
            return int(math.log(num, 2))
    

    The integer truncated base-2 log function will give you the index of the highest bit set. This index N is the base-2 exponent lower bound on the number, because it must be greater than or equal to 2**N