bit-manipulation - 按位标志问题

标签 bit-manipulation bitflags

我有一系列位标志,其顺序类似于 {none=0x00, puppies=0x01, kittens=0x02, cute=0x04, funny=0x08, scary=0x10} 等等。

每当用户进行搜索时,我只是 |= 他们希望的每个标志,例如如果用户想要一些可爱的小猫,我只会search |= cutesearch |= kittens

然而,当我执行搜索操作时,通过遍历并检查该项目的 (flag & search) != 0 的所有项目,它反而返回具有可爱属性或小猫的项目.我怎样才能改变它,让它返回可爱的属性和小猫?

最佳答案

您已经使用 (flag & search) 表达式屏蔽了不相关的标志。现在您只需确保所有 请求的标志都存在。因此,不要执行 (flag & search) != 0,而是执行 (flag & search) == search

关于bit-manipulation - 按位标志问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6458037/

相关文章:

python - 将 I2C 传感器 (DS1624) 读数转换为数字

c++ - 游戏 map 对象属性的位域与多态性

c++ - Bitshift - 需要解释才能理解代码

c - 将 4 字节 int 交织到 8 字节 int

C - 将枚举用于位标志 - 警告 : enumerated type mixed with another type

rust 溢出左移

c# - 用标志方法扩展枚举?

c++ - 在 C++ 中用逻辑 OR ("|") 分隔选项

c - -D name=definition and bitwise operator

php - 处理 PHP 位标志