如何使用 & java中的运算符?移植C代码

发布于 2024-12-28 03:08:04 字数 204 浏览 3 评论 0原文

所以我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

音栖息无 2025-01-04 03:08:04

它应该是 != 0 而不是 == 1

if ((flags & 4) != 0)

这样做的原因是在 C 中,任何非零的值都被认为是 true if 语句,而 Java 强制您使用布尔值。在这种情况下,表达式的计算结果可以为 4 或 0,因此将其与 1 进行比较始终为 false。

It should be != 0 rather than == 1:

if ((flags & 4) != 0)

The reason for this is that in C anything that is not zero is considered true in an if 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.

笑饮青盏花 2025-01-04 03:08:04

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.

腻橙味 2025-01-04 03:08:04

即使在 C 语言中,尝试

if ((flags & 4) != 0)

== 1 也不起作用

Try

if ((flags & 4) != 0)

== 1 will not work even in C

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文