这个布尔值“(number & 1) == 0"是什么意思?意思是? [英] What does this boolean "(number & 1) == 0" mean?

查看:36
本文介绍了这个布尔值“(number & 1) == 0"是什么意思?意思是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 CodeReview 上,我发布了一段工作代码,并要求提供改进建议.我得到的一个是使用布尔方法来检查 ArrayList 是否具有偶数个索引(这是必需的).这是建议的代码:

On CodeReview I posted a working piece of code and asked for tips to improve it. One I got was to use a boolean method to check if an ArrayList had an even number of indices (which was required). This was the code that was suggested:

private static boolean isEven(int number)
{
    return (number & 1) == 0;
}

因为我已经向那个特定的用户请求了很多帮助,所以我决定是时候向 SO 社区提出请求了!我真的不明白这是如何工作的.调用该方法并将 ArrayList 的大小作为参数(即 ArrayList 有 10 个元素,数量 = 10).

As I've already pestered that particular user for a lot of help, I've decided it's time I pestered the SO community! I don't really understand how this works. The method is called and takes the size of the ArrayList as a parameter (i.e. ArrayList has ten elements, number = 10).

我知道一个 & 会同时运行 number 和 1 的比较,但在那之后我迷路了.

I know a single & runs the comparison of both number and 1, but I got lost after that.

我读它的方式是,如果number == 01 == 0,则返回true.我知道第一个不是真的,后者显然没有意义.有人可以帮我吗?

The way I read it, it is saying return true if number == 0 and 1 == 0. I know the first isn't true and the latter obviously doesn't make sense. Could anybody help me out?

我应该补充一点,代码确实有效,以防有人想知道.

推荐答案

记住&"是按位运算.您可能已经意识到这一点,但根据您提出问题的方式,我并不完全清楚.

Keep in mind that "&" is a bitwise operation. You are probably aware of this, but it's not totally clear to me based on the way you posed the question.

话虽如此,理论上的想法是你有一些 int,可以用一些 1 和 0 序列以位表示.例如:

That being said, the theoretical idea is that you have some int, which can be expressed in bits by some series of 1s and 0s. For example:

...10110110

在二进制中,因为它是基数 2,所以当数字的按位版本以 0 结尾时,它是偶数,当它以 1 结尾时,它是奇数.

In binary, because it is base 2, whenever the bitwise version of the number ends in 0, it is even, and when it ends in 1 it is odd.

因此,按位 &上面的 1 是:

Therefore, doing a bitwise & with 1 for the above is:

...10110110 & ...00000001

当然,这是0,所以你可以说原始输入是偶数.

Of course, this is 0, so you can say that the original input was even.

或者,考虑一个奇数.例如,在我们上面的内容上加 1.那么

Alternatively, consider an odd number. For example, add 1 to what we had above. Then

...10110111 & ...00000001

等于 1,因此不等于 0.瞧.

Is equal to 1, and is therefore, not equal to zero. Voila.

这篇关于这个布尔值“(number & 1) == 0"是什么意思?意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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