Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit length of a positive integer in Python

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?

like image 509
user288832 Avatar asked Apr 16 '10 15:04

user288832


People also ask

How many bits is an integer in Python?

To be safe, Python allocates a fixed number of bytes of space in memory for each variable of a normal integer type, which is known as int in Python. Typically, an integer occupies four bytes, or 32 bits.

What is bit length in Python?

Python - Integer bit length Integer bit_length method allows you to query the number of bits required to represent a number's value in binary. You can get the same result by subtracting 2 from the length of the bin string using the len built-in function to handle leading "0b".

Are Python integers 64 bit?

Python, however, doesn't use a fixed number of bit to store integers. Instead, Python uses a variable number of bits to store integers. For example, 8 bits, 16 bits, 32 bits, 64 bits, 128 bits, and so on. The maximum integer number that Python can represent depends on the memory available.

How do you count the number of bits in Python?

Convert number into it's binary using bin() function and remove starting two characters '0b' of output binary string because bin function appends '0b' as prefix in output string. Now print length of binary string that will be the count of bits in binary representation of input number.


1 Answers

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

>>> a = 100 >>> a.bit_length() 7 
like image 108
SilentGhost Avatar answered Nov 04 '22 15:11

SilentGhost