开发者

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.

Y开发者_Python百科et, 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?


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.


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


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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜