Could somebody explain this behavior?
https://jsfiddle.net/td1qtyxL/9/
function checkSignsWeird(a,b){
var output = "";
if(a^b < 0){
output = "The "+a+" and "+b+" have DIFFERENT signs.";
}else{
output = "The "+a+" and "+b+" have the SAME sign.";
}
console.log(output);
}
Basically unless a^b
is stored in a variable (or wrapped in parentheses), it doesn't work.
checkSignsWeird(-50,40);
checkSignsWeird(60,70);
Both produce the same result.
Amy I doing something wrong or is this a bug? Does bitwise work differently when it's in an if clause or when it's elsewhere? I don't often work with bitwise, just thought this was elegant, following up on an answer from here: Check if two integers have the same sign
The "Less Than" (<) has a higher precedence than the bitwise XOR (^): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table
You need to group the operation with parentheses.
Bitwise operators have a lower precedence than comparison operators. See Operator precedence .
That being said, don't write clever code.
function haveSameSign(a, b) {
return (a >= 0 && b >= 0) || (a < 0 && b < 0);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.