Reputation: 15133
Here's a function I wrote in C++ (which works) and am now trying to convert to Java:
static String parseAInstruction(String line) {
int n = getValue(line);
if (n>=0) {
String inst = "0";
for (int i=14; i>=0; --i) {
if (Math.pow(2, i) & n)
inst += "1";
else
inst += "0";
}
return inst;
} else {
return "error";
}
}
This compiles just fine in C++, but when trying to compile in Java, I get the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from int to boolean
at parser.Parser.parseAInstruction(Parser.java:38)
at parser.Parser.main(Parser.java:50)
Looking up bitwise AND in Java, it seems that it should be the same. It shouldn't have anything to do with booleans at all. Can anyone tell me the problem?
Upvotes: 0
Views: 1236
Reputation: 64904
Math.pow
in Java is calculated with a logarithm and an exponentiation (unlike C++, where the compiler often optimizes calls to pow
), both very slow, approximate, floating point operations.
It doesn't even make sense to use here - you're working with bits, so work with bits:
(n & (1 << i)) != 0
is what you're looking for.
Upvotes: 1
Reputation: 156364
In Java you can only use boolean values in if
clauses. So the result of a bitwise AND of two numbers is not valid in an if
statement.
Try this instead: if ((Math.pow(2, i) & n) != 0) {
.
[Edit] However, as commenter @jlordo points out, next you'll have to resolve the problem of doing a bitwise AND between a double and an integer.
Upvotes: 4
Reputation: 32576
The problem is that you can't just use an integer in the conditon expression for if
. you need something like:
if (((int)Math.pow(2, i) & n) != 0)
Upvotes: 3
Reputation: 310840
Trying to do bitwise AND with two ints in Java, but the compiler tries to use them as bools
No it doesn't. The result of the bitwise AND is of type int
. Java requires the expression in an if
statement to be of type boolean, and yours isn't. You need to convert the expression to boolean.
Upvotes: 1
Reputation: 37813
Your problem is here:
if (Math.pow(2, i) & n)
In Java, you need to have a boolean
value as a condition. You probably want:
if (((int)(Math.pow(2, i)) & n) != 0)
The cast to int
is necessary because Math.pow()
will return a double
and the &
operator is only defined for two int
operands.
Upvotes: 2