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

后端 未结 7 1088
猫巷女王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条回答
  • 2020-12-31 06:35

    There is a page with a lot of these types of tricks and hacks. It's written for C, but many of them should work in Python too (though the performance will obviously be different). The bit you want is here and onwards.

    You could try this for example:

    register unsigned int r = 0; // result of log2(v) will go here
    for (i = 4; i >= 0; i--) // unroll for speed...
    {
      if (v & b[i])
      {
        v >>= S[i];
        r |= S[i];
      } 
    }
    

    That looks like it could be converted to Python quite easily.

    0 讨论(0)
提交回复
热议问题