1 -> 1
5 -> 3
10 -> 4
100 -> 7
1000 -> 10
How to count bits for a number in Python?
1 -> 1
5 -> 3
10 -> 4
100 -> 7
1000 -> 10
How to count bits for a number in Python?
def bitcounter(n):
return math.floor(math.log(n,2)) + 1
EDIT fixed so that it works with 1
import math
def number_of_bits(n):
return int(math.log(n, 2)) + 1
>>> 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
In python 3 and and 2.7 there is a int.bit_length()
method:
>>> a = 100
>>> a.bit_length()
7