且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

这个布尔值“(number & 1) == 0"是什么意思?意思是?

更新时间:2021-12-01 23:58:38

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

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.