我有以下输入:
int category;
int ID
ID是这样组成的一个数字:
// CCXXXXNN
ID = 0x12345678;
而类别是介于 0x0 和 0xFF 之间的数字。
我想检查类别是否等于 ID 的 CC 部分。我该怎么做?如有必要,我可以将类别从 int 更改为 uint。
最佳答案
您可以将您拥有的类别值左移到适当的位置,然后将这些位与 ID
中的相应位进行比较:
ID & 0xff000000 == category << 24 // Mask off the high bits of ID, compare with category shifted into those bits
或者您可以右移 ID
的类别位并根据类别值测试它们:
(ID >> 24) & 0xff == category // Put the high bits of ID in the low bits of an int, and mask off that.
就个人而言,我会为这些部分编写访问器函数并使用它们,因为它使事情更具可读性和灵 active ,并且大大更不容易出错。
根据我的经验,当你在胡思乱想时,错误很容易犯,也很难发现。
int get_category(int id) { return (id >> 24) & 0xff; }
int get_xxxx(int id) { return (id >> 16) & 0xffff; }
int get_nn(int id) { return id & 0xff; }
if (get_category(ID) == category && get_nn(ID) < 57)
// and so on
关于c++ - int 变量的位运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21138141/