user499054
user499054

Reputation:

Bitwise flag issue

I have a series of bit flags that order something like {none=0x00, puppies=0x01, kittens=0x02, cute=0x04, funny=0x08, scary=0x10} and so forth.

Whenever a user does a search, I just |= each of the flags that they wish, e.g. if a user wants something of cute kittens, I would just search |= cute and search |= kittens.

Yet, when I carry out the search operation, by looping through and checking all my items where that item's (flag & search) != 0, it instead returns items that have cute attributes OR kittens. How can I change this so it returns cute attributes AND kittens?

Upvotes: 3

Views: 125

Answers (3)

ean5533
ean5533

Reputation: 8994

Instead of looping and checking each flag one at a time, check the search against all the flags combined:

((flag1 | flag2 | flag3) & search) == search

Upvotes: 1

Hernán Eche
Hernán Eche

Reputation: 6899

if((flags&cute) && (flags&kittens))

Upvotes: 1

John Bartholomew
John Bartholomew

Reputation: 6586

You've masked out irrelevant flags with your (flag & search) expression. Now you just have to ensure that all requested flags are present. So, instead of doing (flag & search) != 0, do (flag & search) == search.

Upvotes: 4

Related Questions