views:

79

answers:

1

Hi,

I have a problem while using bitwise in javascript. I don't know if I'm going about this the wrong way. But here goes.

I have 4 main categories. With id 1,2,4,8.

A item in my object has a property with the total of the categories it's a member of. ie.

{ item: { name: 'lorem', c: 7 }} //member of category 1,2,4

I have variable (n) that holds then combined number of active categories. In this case if all categories as active the number is 15.

Now if I change n to 11 (category 1,2,8 is active) I'm trying to determine what items are active. Like this

for (x in items) {
   item = items[x];
   if ((n & item.c) == item.c) {
    //active
   } else {
    //inactive
   }
  }

This doesn't work properly. For example if item.c is 9 (Member of 1,8) the if statement will return true. As it should. But if item.c is 7 (Member of 1,2,4) the if statement returns false. This is my problem. 7 should return true since category 1 and 2 is still active.

Or is this the wrong approach ?

..fredrik

+3  A: 

((n & item.c) == item.c) means "true if all the bits set in item.c are also set in n". If item.c is 7 and n is 11, bit 4 is set in item.c but not in n so the result is false.

It sounds like you want if (n & item.c) { ... }

moonshadow
Ah seems to work. Great !! Thanks!
fredrik
Amarghosh