How to check if a number is a power of 2

后端 未结 25 2190
爱一瞬间的悲伤
爱一瞬间的悲伤 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:16

    Some sites that document and explain this and other bit twiddling hacks are:

    • http://graphics.stanford.edu/~seander/bithacks.html
      (http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2)
    • http://bits.stephan-brumme.com/
      (http://bits.stephan-brumme.com/isPowerOfTwo.html)

    And the grandaddy of them, the book "Hacker's Delight" by Henry Warren, Jr.:

    • http://www.hackersdelight.org/

    As Sean Anderson's page explains, the expression ((x & (x - 1)) == 0) incorrectly indicates that 0 is a power of 2. He suggests to use:

    (!(x & (x - 1)) && x)
    

    to correct that problem.

提交回复
热议问题