Pacha
Pacha

Reputation: 1526

Checking if bit is 1 at a certain position

I have a 4-bit number representation in JavaScript, that represent the 4 times of the day (morning, afternoon, evening, night).

So lets say I have the number 13 (1101) in decimal, it represent that some action has to be done in the night, evening and morning (not afternoon, as the 2nd bit is 0).

What I did so far is get the 4-bit digit that represents the day (1000 is night, 0100 is evening, 0010 is afternoon, 0001 is morning), and what I want to do is create a function that compares the 2 numbers, and returns true if the bit at certain position is equal to one.

I am aware of bitwise operators, but I tried to use them but still no luck.

Upvotes: 0

Views: 2564

Answers (2)

Andrew Kirkegaard
Andrew Kirkegaard

Reputation: 1684

function getTimes (value, time) {
    var times = ["morning", "afternoon", "evening", "night"];

    if (time) {
        return !(~value & 1 << times.indexOf(time));
    }

    return times.filter(function(time, i) { return !(~value & 1 << i); });
}

console.log(getTimes(13, "afternoon")); // false
console.log(getTimes(13)); // ["morning", "evening", "night]

JSFiddle

Upvotes: 0

Alexander
Alexander

Reputation: 23537

Yes, bit-wise. You can use a simple bit-mask test.

var PERIODS_OF_DAY = {
  MORNING: 1, AFTERNOON: 2, EVENING: 4, NIGHT: 8
};

var isPeriodOfDay = function(number, period) {
  return !!(number & period);
};

Testing the number 13:

for (period in PERIODS_OF_DAY) {
    if(PERIODS_OF_DAY.hasOwnProperty(period)) {
        console.log(period + ":", isPeriodOfDay(13, PERIODS_OF_DAY[period]));
    }
}

MORNING: true
AFTERNOON: false
EVENING: true
NIGHT: true 

Upvotes: 2

Related Questions