c++ - int 变量的位运算符

标签 c++ int hex

我有以下输入:

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/

相关文章:

java - Junit 测试方法的日志输出是否正确?

十六进制转二进制

c++ - 如何使用来自 boost.python 的 -fPIC 编译静态库

c++ - Boost.Preprocessor 是否可以实现二维序列?

c - C 中的位域

java - 为什么 1 != 1 返回真?

c++ - 使用 std::is_same<T,const char*>::value 时没有从 'T' 到 'const char*' 的转换

c++ - 二进制文件不可执行-C++和irrklang

c - c中十六进制数的表示

c++ - 将字节数组转换为十六进制时的空格 std::string C++