Bit length of int or long?

Guido van Rossum guido at python.org
Wed May 17 15:05:19 EDT 2000


François Pinard wrote:

> P.S. - Yet, how does one ideally proceed to know the bit length of an
> integer?  I presume `math.frexp' is not too slow at producing the first
> float.  Floats are a bit unexpected in my little integer-only application.

This is not a very commonly requested operation, so there's no built-in for
it.
I would suggest this approach:

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

Regarding your complaint about the docs for frexp(): I've forwarded this to
python-docs at python.org, which is a more appropriate place to send doc
complaints.

If you're interested in knowing more about frex, consult the C math library
manual for frexp() -- that's probably also where I condensed the old docs
from (back in the old days when the assumption was that every Python
programmer was also, first and foremost, a C programmer :-).

-- 
--Guido van Rossum (home page: www.python.org/~guido/)



More information about the Python-list mailing list