N'放大器; (N-1)是什么前pression吗? [英] n & (n-1) what does this expression do?
问题描述
可能显示的文件:结果
<一href=\"http://stackoverflow.com/questions/666647/query-about-working-out-whether-number-is-a-power-of-2\">Query大约工作了数是否是2 结果电源
这是什么功能呢?
N'放大器; (N-1)
- ?在哪里可以这样EX pression使用
n & (n-1)
- where can this expression be used ?
推荐答案
它搞清楚,如果 N
为0或两个完全相同的动力。
It's figuring out if n
is either 0 or an exact power of two.
它的工作原理,因为两个二元权力的形式为 1000 ... 000
和减去1会给你 111 ... 111
。然后,当你和那些一起,你会得到零,如:
It works because a binary power of two is of the form 1000...000
and subtracting one will give you 111...111
. Then, when you AND those together, you get zero, such as with:
1000 0000 0000 0000
& 111 1111 1111 1111
==== ==== ==== ====
= 0000 0000 0000 0000
任何非幂的两个输入值(不为零)会的不的给当您执行操作您零。
Any non-power-of-two input value (other than zero) will not give you zero when you perform that operation.
例如,让我们尝试所有的4位组合:
For example, let's try all the 4-bit combinations:
<----- binary ---->
n n n-1 n&(n-1)
-- ---- ---- -------
0 0000 0111 0000 *
1 0001 0000 0000 *
2 0010 0001 0000 *
3 0011 0010 0010
4 0100 0011 0000 *
5 0101 0100 0100
6 0110 0101 0100
7 0111 0110 0110
8 1000 0111 0000 *
9 1001 1000 1000
10 1010 1001 1000
11 1011 1010 1010
12 1100 1011 1000
13 1101 1100 1100
14 1110 1101 1100
15 1111 1110 1110
您可以看到,只有 0
和两个( 1
, 2的权力
, 4
和 8
)的结果在 0000 /假
位模式,其他均为非零或真正
。
You can see that only 0
and the powers of two (1
, 2
, 4
and 8
) result in a 0000/false
bit pattern, all others are non-zero or true
.
这篇关于N'放大器; (N-1)是什么前pression吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!