Bit length of int or long?

François Pinard pinard at iro.umontreal.ca
Wed May 17 16:41:04 EDT 2000


Guido van Rossum <guido at python.org> écrit:

> > 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 understand that.

> I would suggest this approach:

> 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.  (I'm really after biiig
numbers in this application, but `frexp' is likely to punt when the numbers
exceed the limit of floating representation.)

> python-docs at python.org [...] is a more appropriate place to send doc
> complaints.

Thanks.  I'll try to remember this.  Thanks for your other remarks, as well.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard






More information about the Python-list mailing list