开发者

Javascript bitwise problem

开发者 https://www.devze.com 2022-12-12 14:07 出处:网络
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 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 }开发者_如何学Go} //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


((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) { ... }

0

精彩评论

暂无评论...
验证码 换一张
取 消