views:

155

answers:

4
1 -> 1
5 -> 3
10 -> 4
100 -> 7
1000 -> 10

How to count bits for a number in Python?

+2  A: 
def bitcounter(n):
    return math.floor(math.log(n,2)) + 1

EDIT fixed so that it works with 1

Daniel DiPaolo
This is off by one for powers of two.
Ants Aasma
@Ants Aasma: Are you sure about that? It looks fine to me, assuming that math.log(n, 2) gives a perfectly correct result.
Mark Dickinson
@Ants Aasma: it seems you think that 65536 needs 16 bits. Can you please point us to your PhD thesis? I mean, you have gold in your hands :)
ΤΖΩΤΖΙΟΥ
+8  A: 
import math
def number_of_bits(n):
    return int(math.log(n, 2)) + 1
Ants Aasma
Bear in mind that a floating-point based solution will become inaccurate for large n. Depending on how good the system's log function is, the above solution may also fail for powers of 2.2**48-1 is the smallest integer for which this fails on my system (it gives 49).
Mark Dickinson
+5  A: 
>>> len(bin(1000))-2
10
>>> len(bin(100))-2
7
>>> len(bin(10))-2
4

Note: will not work for negative numbers, may be need to substract 3 instead of 2

S.Mark
+1: Very clever
S.Lott
This will not work with negative numbers though (while it also won't fail on it, opposed to the log-versions)
KillianDS
You are right @KillianDS, I added a note
S.Mark
+11  A: 

In python 3 and and 2.7 there is a int.bit_length() method:

>>> a = 100
>>> a.bit_length()
7
SilentGhost