Java 中的逻辑表示法
绝对基本的 Java 问题,我在 Google 上很难找到。以下是什么意思:
(7 & 8) == 0?
这相当于写作:
7 == 0 || 8 == 0?
我写了一个快速的 main 来测试这一点,似乎是这样。我只是想确保我没有遗漏任何东西。
Absolutely basic Java question which I'm having a hard time finding on Google. What does the following mean:
(7 & 8) == 0?
Is that equivalent to writing:
7 == 0 || 8 == 0?
I wrote a quick main which tests this, and it seems to be the case. I just wanted to make sure I'm not missing anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没有。
&
是按位与。如果两个输入中都设置了相应的位,则它会设置一个位。由于在二进制中,7 是111
,8 是1000
,它们没有共同位,因此结果是0
。对于您所建议的内容,实际上没有任何简写语法,而不是在一行上。有一些解决方法 - 测试
Set
或BitSet
中的成员资格,使用switch
语句 - 但没有一种方法既高效又有效。短至7 == 0 || 8 == 0 。
Nope.
&
is bitwise and. It sets a bit if the corresponding bits are set in both inputs. Since in binary, 7 is111
and 8 is1000
, they have no bits in common, so the result is0
.There isn't really any shorthand syntax for the thing you suggest, not on a single line. There are a few workarounds -- test for membership in a
Set
orBitSet
, use aswitch
statement -- but nothing that's both as efficient and as short as just7 == 0 || 8 == 0
.&
是按位与。给定输入的两个位,以下通过按位 AND 给出位输出:在本例中,
假设您有 26 个而不是 8 个
。按位运算用于提取和操作打包到数字中的字段。
例如,假设您将 3 个字段打包为一个数字,其中两个字段各 4 位 (0..15),一个字段和 3 位字段 (0..7)。
&
is bitwise AND. Given two bits for inputs, the following gives the bit output by bitwise AND:In this case,
Say you had 26 instead of 8.
Bitwise operations are used to extract and manipulate fields packed into a number.
For example, let's say you had a 3 fields packed into one number, two of 4 bits each (0..15), one and 3 bits (0..7).
&
是按位 AND 运算符。这意味着您正在对代表 8 和 7 的位进行 AND 运算:7
->0111
8
->1000
显然结果为 0。
这篇 wikipedia 文章 很好地解释了这一点您的确切示例以及解释其他按位运算符。
The
&
is a bit-wise AND operator. This means that you are ANDing the bits that represent 8 and 7:7
->0111
8
->1000
Which obviously results in 0.
This wikipedia article explains it well with your exact example along with explaining the other bit-wise operators.
这是位比较,工作正常,因为您正在与 7 和 8 进行比较,不能保证与其他情况相比。如果整数中的两个位都匹配,您将得到的结果为“1”而不是“0”。
It is bit comparison, working fine because you are comparing with 7 and 8, not guaranteed with other cases. If both bits in the integers matches you will get results as '1' not '0'.
&如前所述,是有点比较,但也可以用作短路“与”。例如:
总是会抛出错误。但是,
仅当 x 等于 3 时才会抛出错误。如果 x 不等于 3,java 将不会费心计算其余表达式,因为 False &任何事情都会是错误的。
& is a bit comparison, as mentioned, but can also serve as a short-circuiting "and." For instance:
will throw an error all the time. However,
will only throw an error if x equals 3. If x does not equal 3, java will not bother evaluating the rest of the expressions because False & anything will be False.