Javascript 中的按位 & 运算符

Bitwise & Operator in Javascript

我不明白为什么只有 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 ) );
}

== 运算符比 & 具有 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 ) );
}

这是操作顺序的问题。 作为参考,检查 table of JavaScript operator precedence.

== 的概率为 10,而 & 的概率为 9,因此 == 首先被评估。

所以您的代码本质上是在求值:

num & (0x100 == 0x100)

相当于:

num & true

num1 被输出而 num2 不是因为:

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>

我找到了答案,我猜 == 的优先级高于 & 运算符。如果我将代码更改为此,它就可以工作。

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

在 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 

.