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?
In Java you can only use boolean values in
ifclauses. So the result of a bitwise AND of two numbers is not valid in anifstatement.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.