If your version of Python has (≥2.7 for Python 2, ≥3.1 for Python 3), use the bit_length method from the standard library.
Otherwise len(bin(n))-2 as suggested by YOU , quickly (because it is implemented in Python). Note that this returns 1 for 0.
Otherwise, a simple method is to divide by 2 (which is a direct bit shift) and calculate how long it takes to reach 0.
def bit_length(n):
This is much faster (at least for large numbers - quick tests say more than 10 times faster by 1000 digits) shift in whole words at a time, and then go back and work on the bits of the last word.
def bit_length(n): # return the bit size of a non-negative integer if n == 0: return 0 bits = -32 m = 0 while n: m = n n >>= 32; bits += 32 while m: m >>= 1; bits += 1 return bits
In my quick test, len(bin(n)) came out significantly faster than even a version with a word size of size. Although bin(n) builds a line that is immediately discarded, it appears on top because there is an inner loop compiled for machine code. ( math.log even faster, but it doesn’t matter, as it’s wrong.)
Gilles Feb 03 '12 at 19:11 2012-02-03 19:11
source share