Python 3.1+Numbers & mathfunction
int.bit_length
bits
Return the number of bits needed to represent the absolute value in binary (0 for 0).
Syntax
n.bit_length()
Negatives are taken by absolute value, so the sign never affects the result. For n > 0 this equals floor(log2(n)) + 1, but unlike math.log2 it is exact: log2 converts the int to a float first, and 2**64 - 1 rounds to exactly 64.0, so the formula is off by one while bit_length still returns 64.
Examples
print((255).bit_length()) # → 8
print((1024).bit_length()) # → 11
print((0).bit_length()) # → 0
See also
Open in the full glossarydocs.python.orgReport an inaccuracy