1

This question offers two approaches to computing bit length of an int:

  1. All versions: len(bin(x))-2
  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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

6 Comments

the problem with this approach is that the check is done on each invocation
@sds is that a problem?
this is definitely an aesthetic problem for me; it could also be a performance issue.
@sds updated with an alternative; testing with timeit suggests that the bit_length version is faster, so I'd go with that where possible.
thanks, any reason to use lambda instead of def (IOW, is there a problem with non-top-level def?)
|
0

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

2 Comments

Although portable, this is pretty slow; it takes four times as long as the len version and seven times as long as using bit_length.
Yes, though I thought to add it in just for plain portablitity :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.