How to check if a number is a power of 2

后端 未结 25 1946
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:30

Today I needed a simple algorithm for checking if a number is a power of 2.

The algorithm needs to be:

  1. Simple
  2. Correct for any ulong
25条回答
  •  滥情空心
    2020-11-22 04:15

    bool isPowerOfTwo(int x_)
    {
      register int bitpos, bitpos2;
      asm ("bsrl %1,%0": "+r" (bitpos):"rm" (x_));
      asm ("bsfl %1,%0": "+r" (bitpos2):"rm" (x_));
      return bitpos > 0 && bitpos == bitpos2;
    }
    

提交回复
热议问题