Search code examples
bit-manipulationbitflags

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?


Solution

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