Search code examples
javascriptbitwise-and

Bitwise AND operations in Javascript


I make a project that reads value from a remote JSON. In this project the remote JSON can give me with one variable 16 different types of alarm. The implementation is by a bynary 16bit value expressed in int. So if there is the third alarm it should return me 8 (bynary 1000) and if the second,eigth and tenth alarm is up it return me 1284 (binary 10100000100). Well when there is no alarm it returns me 0. So, I create a function in JS (accordly to here) that passing the value returned (8/1284/0 in the example) returns me a simple true or false if there is an alarm. The function is pretty simple:

function IsOnAlarm(passedVal) {
    if (passedVal & 0) {
        return false;
    } else {
        return true;
    }
}

but it does not function :-( I create a JSFiddle that shows the problem. How can I solve it? Thanks in advance.


Solution

  • Well as far as I understand you just need to check whether the value is 0. There's no need for any bitwise operation.

    function IsOnAlarm(passedVal) {
        return passedVal != 0;
    }
    

    Side note: passedVal & 0 is always 0 no matter what passedVal is (that's why it always goes to else).