为什么如果(N&安培; -n)== N,然后按n为2的幂? [英] Why if (n & -n) == n then n is a power of 2?

查看:142
本文介绍了为什么如果(N&安培; -n)== N,然后按n为2的幂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

线java.util.Random中源说的294

if ((n & -n) == n) // i.e., n is a power of 2
    // rest of the code

这是为什么?

推荐答案

的描述是不完全准确,因为(0安培; -0)== 0 0,但为不是两个电源。一个更好的办法可以说是

The description is not entirely accurate because (0 & -0) == 0 but 0 is not a power of two. A better way to say it is

((N安培; -n)== n)的当n为二的幂,或两种,或零功率的负

((n & -n) == n) when n is a power of two, or the negative of a power of two, or zero.

如果n为二的幂,则n在二进制是一个1随后零。
-n以二的补是逆+ 1,因此位线高达从而

If n is a power of two, then n in binary is a single 1 followed by zeros. -n in two's complement is the inverse + 1 so the bits lines up thus

 n      0000100...000
-n      1111100...000
 n & -n 0000100...000

要明白为什么这项工作,可以考虑补的逆+ 1 -n ==〜N + 1

To see why this work, consider two's complement as inverse + 1, -n == ~n + 1

n          0000100...000
inverse n  1111011...111
                     + 1
two's comp 1111100...000

因为你通过携带一个一路增加一个时,为了获得二进制补码。

since you carry the one all the way through when adding one to get the two's complement.

如果N的以外的任何其他两个与匕首电源;那么结果将是缺少了一点,因为补不会有最高位设置,由于携带。

If n were anything other than a power of two† then the result would be missing a bit because the two's complement would not have the highest bit set due to that carry.

&匕首​​; - 或零或二的幂的一个负...如在顶部说明

† - or zero or a negative of a power of two ... as explained at the top.

这篇关于为什么如果(N&安培; -n)== N,然后按n为2的幂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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