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

查看:432
本文介绍了这个布尔“(数字& 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)。

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).

我知道一个& 运行数字和1的比较,但之后我迷路了。

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

我读它的方式,它说的是如果 number == 0 1 == 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,因此不等于零。 Voila。

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

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

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