This question offers two approaches to computing bit length of an int
:
- All versions:
len(bin(x))-2
- 2.7+:
x.bit_length()
I need my code to work with 2.6+, so I cannot use the second solution.
Is this the best I can do?
import sys
if sys.hexversion < 0x02070000
def bitlen(x): return len(bin(x))-2
else:
def bitlen(x): return x.bit_length()
The alternative is
try:
(1).bit_length()
def bitlen(x): return x.bit_length()
except AttributeError:
def bitlen(x): return len(bin(x))-2