Bit length of a positive integer in Python

后端 未结 7 2064
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 05:47
1 = 0b1 -> 1
5 = 0b101 -> 3
10 = 0b1010 -> 4
100 = 0b1100100 -> 7
1000 = 0b1111101000 -> 10
…

How can I get the bit length of an int

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 06:32

    If your Python version has it (≥2.7 for Python 2, ≥3.1 for Python 3), use the bit_length method from the standard library.

    Otherwise, len(bin(n))-2 as suggested by YOU is fast (because it's implemented in Python). Note that this returns 1 for 0.

    Otherwise, a simple method is to repeatedly divide by 2 (which is a straightforward bit shift), and count how long it takes to reach 0.

    def bit_length(n): # return the bit size of a non-negative integer
        bits = 0
        while n >> bits: bits += 1
        return bits
    

    It is significantly faster (at least for large numbers — a quick benchmarks says more than 10 times faster for 1000 digits) to shift by whole words at a time, then go back and work on the bits of the last word.

    def bit_length(n): # return the bit size of a non-negative integer
        if n == 0: return 0
        bits = -32
        m = 0
        while n:
            m = n
            n >>= 32; bits += 32
        while m: m >>= 1; bits += 1
        return bits
    

    In my quick benchmark, len(bin(n)) came out significantly faster than even the word-sized chunk version. Although bin(n) builds a string that's discarded immediately, it comes out on top due to having an inner loop that's compiled to machine code. (math.log is even faster, but that's not important since it's wrong.)

提交回复
热议问题