Number of bits/sizeof int

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Jan 31 02:37:16 EST 2009


En Sat, 31 Jan 2009 05:03:27 -0200, Jon Clements <joncle at googlemail.com>  
escribió:

> This has a certain amount of irony (as this is what I'm pretty much
> after):-
>> From http://docs.python.org/dev/3.0/whatsnew/3.1.html:
> "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.

I'm sure *everyone* will now post his favourite algorithm... If you search  
the archives, you'll find *tons* of versions. Ok, my take:

def number_of_bits(num):
   assert num>=0
   nbits = 1
   max = 2
   while max<=num:
     nbits += 1
     max += max
   return nbits

-- 
Gabriel Genellina




More information about the Python-list mailing list