按位& Javascript中的运算符

时间:2015-03-20 16:53:47

标签: javascript bitwise-operators

我不明白为什么只有num1才会打印输出。我在这里错过了什么吗?

var num1 = 0x200127;
var num2 = 0x200124;
    
if(num1 & 0x100 == 0x100){
    console.log("num1: " + (num1 & 0x100 ) );
}
if(num2 & 0x100 == 0x100){
    console.log("num2: " + (num2 & 0x100 ) );
}

4 个答案:

答案 0 :(得分:2)

这是操作顺序的问题。 如需参考,请查看table of JavaScript operator precedence

==的预测值为10,而&的预测值为9,因此首先评估==

所以你的代码基本上是在评估:

num & (0x100 == 0x100)

相当于:

num & true
输出

num1num2不是因为:

0x200127 & true == 1 (true)
0x200124 & true == 0 (false)

尝试将您的按位操作放在括号中,因为grouping operator具有最高优先级。

if((num1 & 0x100) == 0x100){
    console.log("num1: " + (num1 & 0x100 ) );
}
if((num2 & 0x100) == 0x100){
    console.log("num2: " + (num2 & 0x100 ) );
}

测试如下:

var num1 = 0x200127,
  num2 = 0x200124,
  output = document.getElementById('output');

if ((num1 & 0x100) == 0x100) {
  output.innerHTML += "<p>num1: " + (num1 & 0x100) + "</p>";
}
if ((num2 & 0x100) == 0x100) {
  output.innerHTML += "<p>num2: " + (num2 & 0x100) + "</p>";
}
<div id="output"></div>

答案 1 :(得分:1)

==运算符的higher precedence大于&。所以

x & y == z

评估为

x & (y == z)

在第二种情况下,这会使条件评估为0,从而false

num2 & 0x100 == 0x100
0x200124 & 0x100 == 0x100
0x200124 & true
0x200124 & 1
0

您想使用分组运算符更改优先级:

if((num1 & 0x100) == 0x100){
    console.log("num1: " + (num1 & 0x100 ) );
}
if((num2 & 0x100) == 0x100){
    console.log("num2: " + (num2 & 0x100 ) );
}

答案 2 :(得分:0)

我找到了答案,我猜= =的优先级高于&amp;运营商。如果我将代码更改为此,则可以正常工作。

&#13;
&#13;
var num1 = 0x200127;
var num2 = 0x200124;
    
if(num1 & 0x100 == 0x100){
    console.log("num1: " + (num1 & 0x100 ) );
}
if((num2 & 0x100) == 0x100){
    console.log("num2: " + (num2 & 0x100 ) );
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

在javascript ==具有更高的优先顺序,然后按位AND运算符因此比较0x100 == 0x100 always result in 1是真的,

if we do Bitwise AND of 1 with even number, result will always be 0. 
And if we do Bitwise AND of 1 with odd number, result will always be 1