Bit length of int or long?

Dan Schmidt dfan at harmonixmusic.com
Wed May 17 18:20:48 EDT 2000


François Pinard <pinard at iro.umontreal.ca> writes:

| Guido van Rossum <guido at python.org> écrit:
| 
| > def bitl(x):
| >     assert x >= 0
| >     n = 0
| >     while x > 0:
| >         n = n+1
| >         x = x>>1
| >     return n
| 
| Sounds rather slow, especially for big numbers.

Well, you can always do something like this:

def bitl(x):
    assert x >= 0
    n = 0
    while x > 256:
        n = n + 8
        x = x >> 8
    while x > 0:
        n = n + 1
        x = x >> 1
    return n

-- 
Dan Schmidt | http://www.dfan.org



More information about the Python-list mailing list