开发者

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

开发者 https://www.devze.com 2023-02-18 08:04 出处:网络
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开发者_StackOverflow中文版 lower bounderies.

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开发者_StackOverflow中文版 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.


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


You can use the logarithm with base 2:

result = math.floor(math.log(x, 2))


I just ran into the same "problem" and decided to solve it a different way.

As you are looking for the base-2 log, per definition the binary representation of the powers of 2 will each only contain one 1 and the rest 0's:

>>> bin(64)
'0b1000000'
>>> bin(16)
'0b10000'

Moreover, the position of the 1 (as counted from the right) will be the power you are looking for + 1 (as the first bit is the 2**0-bit).

Therefore, you can solve this problem using:

>>> len(bin(64)) - 3
6
>>> len(bin(37)) - 3
5

the 3 in this case is to subtract the length of the prefix '0b' and the one bit for position 0.

PS. I know this question is very old, but as it happens to be high in the Google results, I thought it would not be bad to post another method either.

PS2. I did not do a performance test, but in my case as I was doing bit operations anyway, it seemed to be more fitting, also without the need to import another library.

0

精彩评论

暂无评论...
验证码 换一张
取 消