Reputation: 60062
This question offers two approaches to computing bit length of an int
:
len(bin(x))-2
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
Upvotes: 1
Views: 202
Reputation: 13
This would work on 2.6 and below as well as above.
def bitlen(int_type):
length = 0
while (int_type):
int_type >>= 1
length += 1
return(length)
# and then
bitlen(0b10000) # --> 5
Check out, https://wiki.python.org/moin/BitManipulation, for further reading
Upvotes: 0
Reputation: 122154
I would probably write it as:
def bitlen(x):
"""The bit length of the integer x."""
try:
return x.bit_length()
except AttributeError: # I guess!
return len(bit(x)) - 2
This removes the need for an explicit version check. If you want to factor the check out of the function, perhaps:
if hasattr(1, 'bit_length'):
bitlen = lambda x: x.bit_length()
else:
bitlen = lambda x: len(bit(x)) - 2
Upvotes: 1