如何为2的幂这个位运算检查? [英] How does this bitwise operation check for a power of 2?

查看:209
本文介绍了如何为2的幂这个位运算检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看一些code这应该是微不足道的 - 但我的数学是惨遭失败在这里我

I'm looking at some code which should be trivial -- but my math is failing me miserably here.

下面是一个检查一个条件,如果一个号码,如果使用下列2的功率:

Here's a condition that checks if a number if a power of 2 using the following:

if((num != 1) && (num & (num - 1))) { /* make num pow of 2 */ }

我的问题是,如何使用按位和NUM和num之间 - 1确定一个数是2的幂

My question is, how does using a bitwise AND between num and num - 1 determine if a number is a power of 2?

推荐答案

2的幂减1,所有的人:( 2 N - 1 = 111 .... b 的)

Any power of 2 minus 1 is all ones: (2 N - 1 = 111....b)

2 = 2^1.  2-1 = 1 (1b)
4 = 2^2.  4-1 = 3 (11b)
8 = 2^3.  8-1 = 7 (111b)

以8为例。 1000安培; 0111 = 0000

Take 8 for example. 1000 & 0111 = 0000

这样的前pression测试如果一个数是不是2的力量。

So that expression tests if a number is NOT a power of 2.

这篇关于如何为2的幂这个位运算检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆