1

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.

1
  • If you dont want to know the specific values return passedVal!=0 Commented Mar 13, 2014 at 8:05

5 Answers 5

2

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).

Sign up to request clarification or add additional context in comments.

Comments

1

You can do it like

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

Check this http://jsfiddle.net/KQH43/3/

Comments

0

The AND operator always return false if one of the operands is zero, see below:

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1

The easiest way to rewrite your function is as follows:

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

Explanation: the double negation operation (!!) allows you to cast the input to boolean. Any non-zero value will evaluate to true, zero evaluates to false.

Comments

0

Check this jsfiddle, it is using bitwise AND comparison.

I've modified your function to make it easier to understand:

function AreAlarmsOn(alarmsToCheck, alarmState) {
    return and(alarmsToCheck, alarmState)!=0;
}

It takes alarmsToCheck and checks its bits against alarmState bits, alarmsToCheck can have bits for several alarms if you need to check multiple alarms.

Comments

0

Is this what you're looking for?

var getFlags = function(val) {
    var results = [];
    for (var i = 0; i < 16; i++) {
        results.push(!!((val >> i) & 1));
    }
    return results;
};

var flags = getFlags(1284);

flags[2] //=> true
flags[8] //=> true
flags[10] //=> true
// all other values ==> false / undefined

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.