Using a bitwise & inside an if statement

2019-02-16 14:41发布

In C, I can write an if-statement

if (firstInt & 1)

but when I try and do the same in Java, the compiler tells me "incompatible types" and says I need a boolean instead of an int. Is there any way to write that C code in Java?

2条回答
我只想做你的唯一
2楼-- · 2019-02-16 15:05

Any of the following should work for you:

if ((firstInt & 1) != 0)
if ((firstInt & 1) > 0)
if ((firstInt & 1) == 1)
查看更多
beautiful°
3楼-- · 2019-02-16 15:14

In C an integer expression can be used implicitly as a boolean expression (although I would argue that it is a bad idea), where zero is false and any non-zero value is true.

In Java that is not allowed so you have to make the expression explicitly boolean by comparing the integer result to some other integer value or expression using a comparison operator.

查看更多
登录 后发表回答