如何使用 & java中的运算符?移植C代码
所以我在 C 中得到了这个简单的代码。
if (flags & 4)
现在,当我将该行移植到 java 时:
if ((flags & 4) == 1)
它不会触发。将C代码移植到Java的正确方法是什么?我做错了什么 &操作员?
So I've got this simple code in C.
if (flags & 4)
Now when I port the line to java:
if ((flags & 4) == 1)
It doesn't trigger. Whats the correct way to port the C code to Java? What am I doing wrong with the & operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它应该是
!= 0
而不是== 1
:这样做的原因是在 C 中,任何非零的值都被认为是
true
if
语句,而 Java 强制您使用布尔值。在这种情况下,表达式的计算结果可以为 4 或 0,因此将其与 1 进行比较始终为 false。It should be
!= 0
rather than== 1
:The reason for this is that in C anything that is not zero is considered
true
in anif
statement, while Java forces you to use Booleans. In this case, the expression can evaluate either to 4 or to 0, so comparing it with 1 is always false.if ((flags & 4)==4)
当您使用按位 and 来“屏蔽”除 1 之外的所有位时,结果不会是 1,而是该位你检查过。
if ((flags & 4)==4)
When you use bitwise and to "mask" all the bits except one, the result isn't going to be one, it's going to be the bit you checked for.
即使在 C 语言中,尝试
== 1
也不起作用Try
== 1
will not work even in C