XOR 和 NOT-EQUAL-TO 有什么区别?
我的问题以 Java 为例,但我想它可能适用于所有人。
在比较布尔值时,XOR 运算符(Java 中的 ^
)和不等于运算符(Java 中的!=
)之间有什么实际区别吗?
我在这里评估了一些东西,但我只是一直想知道(看起来很奇怪,两件事是相等的)......并且在网上没有找到任何东西。只是在某个论坛上的一次讨论很快就结束了,没有任何结果。
My question uses Java as an example, but I guess it applies to probably all.
Is there any practical difference between the XOR operator (^
in Java) and the not-equal-to operator (!=
in Java), when comparing booleans?
I evaluated things here, but I just kept wondering (seems weird, two things equal)... and didn't find anything on the net. Just one discussion in some forum that ended quickly without any result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对于布尔值,它们的含义是相同的 - 尽管有一个用于 XOR 的复合赋值运算符:
对于不等式,没有等效的复合赋值运算符。
至于为什么它们都可用 - XOR 不可用只是因为它与不等式的工作方式相同,这会很奇怪。从逻辑上来说它应该在那里,所以就是这样。对于非布尔类型,结果是不同的,因为它是不同的结果类型,但这并不意味着删除布尔值的 XOR 是有意义的。
For Boolean values, they mean the same thing - although there's a compound assignment operator for XOR:
There's no equivalent compound assignment operator for inequality.
As for why they're both available - it would be odd for XOR not to be available just because it works the same way as inequality. It should logically be there, so it is. For non-Boolean types the result is different because it's a different result type, but that doesn't mean it would make sense to remove XOR for
boolean
.如 Java语言规范:
此外,如果您尝试查看一个简单片段的字节码:
您会得到:
这确保了,除了相同的语义之外,在实现上没有任何实际的实际差异。 (你还可以看到内部使用int来存储布尔值)
As stated in the Java Language Specification:
In addition if you try looking at bytecode of a simple snippet:
you obtain:
This assures that, in addition to the same semantics, there's no any actual practical difference in implementation. (you can also see that internally ints are used to store boolean values)
是的,您可以使用 XOR 来测试布尔值是否相等,尽管代码不太直观:
if (x ^ y)
与if (x != y)
。Yes, you can use XOR to test booleans for (in)equality, although the code is less intuitive:
if (x ^ y)
versusif (x != y)
.对于布尔值,应该没有区别。您应该选择更适合您的操作感觉的选项。
示例:
这里
XOR
会给出相同的结果,但不会反映真正的代码意图。With boolean values, there should be no difference. You should choose whichever is more appropriate for your sense of operation.
Example:
Here
XOR
would give the same result, but will not reflect the real code intention.在这种情况下,它们应该本质上是相同的。
They should be essentially the same in this case.
有很大的区别,XOR 在位级别工作,将差异保持为 1,
所以 0b0011 异或 0b1101 => 0b1110
问候,
//t
There's a big difference, XOR works at bit-level, keeping differences as ones,
so 0b0011 xor 0b1101 => 0b1110
regards,
//t