Bit length of int or long?

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


Hi, people.

I would have vaguely hoped that len(3) or len(3L) gives me the number of bits
taken by the integer 3, but that function is not available over integers.
The closest thing I found is `math.frexp', but the library reference for
1.5.2 is much too terse (and probably wrong) about it.  It says:

   frexp(x)
       Return the mantissa and exponent for x.  The mantissa is positive.

With Python 1.6a1, I may get a negative mantissa:

>>> math.frexp(-1024)
(-0.5, 11)

The manual should say that the exponent is an exponent of two.  It should
also say that the mantissa is returned as a float for which the absolute
value is in the closed-opened interval [0.5, 1.0), and which has the sign
of the argument.  This is presuming I'm correctly guessing how it works,
but as an apparent special case, `math.frexp(0)' returns `(0.0, 0)'.

If I had a precise specification for `math.frexp', like above, I could
use it a bit more seriously.  Programs should ideally not rely on guess
work :-).  Could the documentation be amended and made precise for this?


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.

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






More information about the Python-list mailing list