Justin C.
Justin C.

Reputation: 49

Bitwise & Operator in Javascript

I don't understand why only num1 would print output when they both should be. Am I missing something here?

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

Upvotes: 1

Views: 265

Answers (4)

Himanshu Goel
Himanshu Goel

Reputation: 594

In javascript == has higer precedence order then bitwise AND operator thus on comparison of 0x100 == 0x100 always result in 1 that is true, and

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 

.

Upvotes: 0

showdev
showdev

Reputation: 29168

This is an issue with order of operations. For reference, check the table of JavaScript operator precedence.

== has a precidence of 10 while & has a precidence of 9, so == gets evaluated first.

So your code is essentially evaluating:

num & (0x100 == 0x100)

Which is equivalent to:

num & true

num1 is outputted while num2 is not because:

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

Try putting your bitwise operations in parenthesis, as the grouping operator has the highest precedence of all.

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

Test it below:

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>

Upvotes: 3

Justin C.
Justin C.

Reputation: 49

I found the answer, I guess that == has a higher precedence than the & operator. if I change the code to this, it works.

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

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816462

The == operator has a higher precedence than &. So

x & y == z

is evaluated as

x & (y == z)

In the second case, that makes the condition evaluated to 0 and thus false:

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

You want to change the precedence by using the grouping operator:

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

Upvotes: 2

Related Questions