Finding the exponent of n = 2**x using bitwise operations [logarithm in base 2 of n]

后端 未结 7 1093
猫巷女王i
猫巷女王i 2020-12-31 05:47

Is there a straightforward way to extracting the exponent from a power of 2 using bitwise operations only?

EDIT: Although the question was originall

7条回答
  •  Happy的楠姐
    2020-12-31 06:18

    Late to the party, but how about int.bit_length(n) - 1? You asked for straightforward, and that seems the simplest to me. The CPython implementation looks reasonably performant.

    • Reference documentation
    • CPython source code

提交回复
热议问题