Number of bits/sizeof int

John Machin sjmachin at lexicon.net
Mon Feb 2 16:36:22 EST 2009


On Feb 3, 6:50 am, Mark Wooding <m... at distorted.org.uk> wrote:
> Jon Clements <jon... at googlemail.com> writes:
> > "The int() type gained a bit_length method that returns the number of
> > bits necessary to represent its argument in binary:"
>
> > Any tips on how to get this in 2.5.2 as that's the production version
> > I'm stuck with.
>
> def nbits(x):
>
>   ## Special cases.
>   if x == 0: return 0
>   elif x < 0: x = -x

3 can be represented in 2 bits and at the same time -3 can be
represented in 2 bits?? But 2 bits can support only 2 ** 2 == 4
different possibilities, and -3 .. 3 is 7 different integers.

>   ## Find upper bound of the form 2^(2^n) >= x.

Possibly you mean 2 ** ( 2 ** n) >= x



More information about the Python-list mailing list