javascriptbit-manipulationbitwise-operatorsnegation

Equality negation to determine Least Significant Bit


Basically, I want to check if the last significant bit is a 0. I already had a condition to test if the bit is set or not (or at least, I believe so) :

cells[x + y * cols] & 1 === 1

At some point, I need the negation of this, so I thought :

cells[x + y * cols] & 1 === 0

But I didn't get the expected result. So I just :

(!cells[x + y * cols] & 1 === 1)

Which seems more appropriate according to the expected result. I don't get the expected result actualy, in both case. Maybe the problem comes from somewhere else or maybe I'm just misunderstanding the use of the bitwise operator.

So first of all, why these line are differents:

console.log(!(4 & 1 === 1)); // true
console.log(4 & 1 === 0); // 0

I mean, obviously the LSB of 4 is 0. I would say the first one is the one I need though...


Solution

  • You need to wrap the 4 & 1 into parenthesis like so

    console.log((4 & 1) === 0);
    

    Because if you don't, it prioritizes 1 === 0 which is false and then 4 & false which is the same as 4 & 0.