Using a bitwise & inside an if statement

user1310650 picture user1310650 · Apr 8, 2012 · Viewed 7.5k times · Source

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?

Answer

Tim Cooper picture Tim Cooper · Apr 8, 2012

Any of the following should work for you:

if ((firstInt & 1) != 0)
if ((firstInt & 1) > 0)
if ((firstInt & 1) == 1)