0

In python I want to calculate the number of bits required to represent an unsigned number. For eg:

2 --> 2 bits
3 --> 2 bits
10 --> 4 bits

I am simply calculating it as follows len( bin( n ) ) - 2

Is there any other better way to calculate this ? purely using bit manipulation so that I can use it on other languages as well ?

user881300
  • 212
  • 1
  • 9
  • Use `int.bit_length(integer)` python2.7, `a=10 a.bit_length()` python3 – Kenly Dec 28 '15 at 14:50
  • Your method looks ok, you could also use `ceil(log(n, 2))` but that may be more expensive. – ilent2 Dec 28 '15 at 14:50
  • 1
    Important to consider if you are using signed or unsigned numbers too... – ilent2 Dec 28 '15 at 14:51
  • @zetysz I want to use just bit manipulation so that I can port it to other language. – user881300 Dec 28 '15 at 14:52
  • @ilent2 just unsigned numbers – user881300 Dec 28 '15 at 14:52
  • @user881300: Ultimately, working with bits is a very low-level thing to do, and high-level languages are going to have very different ways to support it (including no support at all in some cases). In most cases, you'll have to find out how the target language does it anyway. If you *truly* want portability, you should definitely *not* ask for a bit-twiddling trick. – John Y Dec 28 '15 at 15:10
  • Related: http://stackoverflow.com/questions/2654149/count-bits-of-a-integer-in-python – John Y Dec 28 '15 at 15:27

2 Answers2

2

The easiest way is to use the .bit_length() method of int type:

>>> for n in (2, 10):
...     print(n.bit_length())
... 
2
4

If you want to do the bit twiddling yourself, you could use the following function:

def bit_length(n):
    bits = 0
    while n:
        bits += 1
        n >>= 1
    return bits
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • is there a way I can avoid python specific method and find it using just bit manipulation or something so that I can port it to other language like C ? – user881300 Dec 28 '15 at 14:55
2

If you really want a bit to do it, then

count=0
while(n!=0):
 n=n>>1
 count+=1
Untitled123
  • 1,317
  • 7
  • 20