Bit length of a positive integer in Python

user288832 picture user288832 · Apr 16, 2010 · Viewed 76k times · Source
1 = 0b1 -> 1
5 = 0b101 -> 3
10 = 0b1010 -> 4
100 = 0b1100100 -> 7
1000 = 0b1111101000 -> 10
…

How can I get the bit length of an integer, i.e. the number of bits that are necessary to represent a positive integer in Python?

Answer

SilentGhost picture SilentGhost · Apr 16, 2010

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

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