Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


2 Answers

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.

like image 180
John Bartholomew Avatar answered Sep 26 '26 16:09

John Bartholomew


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

like image 27
Hernán Eche Avatar answered Sep 26 '26 15:09

Hernán Eche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!