Query about working out whether number is a power of 2

后端 未结 4 1307
情歌与酒
情歌与酒 2020-12-07 04:59

Using the classic code snippet:

if (x & (x-1)) == 0

If the answer is 1, then it is false and not a power of 2. However, working on 5 (not a power of 2) a

4条回答
  •  暖寄归人
    2020-12-07 05:38

    You need refresh yourself on how binary works. 5 is not represented as 0001 1111 (5 bits on), it's represented as 0000 0101 (2^2 + 2^0), and 4 is likewise not 0000 1111 (4 bits on) but rather 0000 0100 (2^2). The numbers you wrote are actually in unary.

    Wikipedia, as usual, has a pretty thorough overview.

提交回复
热议问题