0

Basically I wanted to try bitwise manipulation in Java, and it seems that C and Java do not handle the bits in the same way.

public static boolean checkIsPowerOfTwo(int x) {
    return ( !(x & (x-1)) );
}

This function, taken from here is not working as expected in Java, so my understanding of bitwise operators is clearly not right for Java.

The error I get is

CheckIsPowerOfGivenNumber.java:13: error: bad operand type int for unary operator '!'
return ( !(x & (x-1)) );
         ^

How can I correct this?

2
  • That is c code, not Java. What have you found about operators in Java. Why do you expect it to work? Nov 29, 2015 at 7:23
  • ! is a boolean operator. You're trying to apply it on an integer.
    – JB Nizet
    Nov 29, 2015 at 7:24

2 Answers 2

2

Java type system is more strict comparing to C. In particular it does not perform automatic conversion from int to boolean (which actually helps to prevent many stupid bugs). The ! operator in Java is applicable for boolean type only. Use == operator to explicitly compare the value with 0:

public static boolean checkIsPowerOfTwo(int x) {
    return (x & (x-1)) == 0;
}

Actually (x & (x-1)) == 0 is a valid C code as well, but looks definitely less cryptic. I would recommend writing on C this way as well.

0

Actually the bitwise part is correct the problem is ! is a logical not --- the bitwise not (comm operator is ~. Having said that you still have the probem of convert your int to a boolean.

    return ((~(x &(x-1)) == 0);
1
  • That doesn't work, it compiles but changing !something to ~something == 0 is obviously wrong
    – harold
    Nov 29, 2015 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.