Bit length of int or long?

Dennis Lee Bieber wlfraed at ix.netcom.com
Thu May 18 05:14:37 CEST 2000


On Wed, 17 May 2000 19:05:19 GMT, Guido van Rossum <guido at python.org>
declaimed the following in comp.lang.python:


> This is not a very commonly requested operation, so there's no built-in for
> it.
> I would suggest this approach:
> 
> def bitl(x):
>     assert x >= 0
>     n = 0
>     while x > 0:
>         n = n+1
>         x = x>>1
>     return n
>

	How about...

	import math


	def bitlen(x):
		assert x > 0
		return math.floor (math.log10(x) / math.log10(2) ) + 1


>>> for j in range(1,20):
... 	print j, bitlen(j)
... 
1 1.0
2 2.0
3 2.0
4 3.0
5 3.0
6 3.0
7 3.0
8 4.0
9 4.0
10 4.0
11 4.0
12 4.0
13 4.0
14 4.0
15 4.0
16 5.0
17 5.0
18 5.0
19 5.0
>>> 
>>> bitlen(sys.maxint * 2L)
32.0
>>> bitlen(sys.maxint)
31.0
>>> 

--
 > ============================================================== <
 >   wlfraed at ix.netcom.com  | Wulfraed  Dennis Lee Bieber  KD6MOG <
 >      wulfraed at dm.net     |       Bestiaria Support Staff       <
 > ============================================================== <
 >        Bestiaria Home Page: http://www.beastie.dm.net/         <
 >            Home Page: http://www.dm.net/~wulfraed/             <



More information about the Python-list mailing list