Issue #3439: add bit_length method to int and long.

Thanks Fredrik Johansson and Victor Stinner for code,
Raymond Hettinger for review.
This commit is contained in:
Mark Dickinson 2008-12-17 16:14:37 +00:00
parent d0c3515bc5
commit 1a707981c8
8 changed files with 239 additions and 1 deletions

View file

@ -447,6 +447,41 @@ Notes:
A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
Additional Methods on Integer Types
-----------------------------------
.. method:: int.bit_length()
.. method:: long.bit_length()
For any integer ``x``, ``x.bit_length()`` returns the number of
bits necessary to represent ``x`` in binary, excluding the sign
and any leading zeros::
>>> n = 37
>>> bin(n)
'0b100101'
>>> n.bit_length()
6
>>> n = -0b00011010
>>> n.bit_length()
5
More precisely, if ``x`` is nonzero then ``x.bit_length()`` is the
unique positive integer ``k`` such that ``2**(k-1) <= abs(x) <
2**k``. Equivalently, ``x.bit_length()`` is equal to ``1 +
floor(log(x, 2))`` [#]_ . If ``x`` is zero then ``x.bit_length()``
gives ``0``.
Equivalent to::
def bit_length(self):
'Number of bits necessary to represent self in binary.'
return len(bin(self).lstrip('-0b'))
.. versionadded:: 2.7
Additional Methods on Float
---------------------------
@ -2648,6 +2683,11 @@ types, where they are relevant. Some of these are not reported by the
.. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
similarly for tuples.
.. [#] Beware of this formula! It's mathematically valid, but as a
Python expression it will not give correct results for all ``x``,
as a consequence of the limited precision of floating-point
arithmetic.
.. [#] They must have since the parser can't tell the type of the operands.
.. [#] To format only a tuple you should therefore provide a singleton tuple whose only

View file

@ -66,7 +66,23 @@ Other Language Changes
Some smaller changes made to the core Python language are:
* List of changes to be written here.
* The :func:`int` and :func:`long` types gained a ``bit_length``
method that returns the number of bits necessary to represent
its argument in binary::
>>> n = 37
>>> bin(37)
'0b100101'
>>> n.bit_length()
6
>>> n = 2**123-1
>>> n.bit_length()
123
>>> (n+1).bit_length()
124
(Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)
.. ======================================================================