【问题标题】:bit operator on int variablesint 变量的位运算符
【发布时间】:2014-02-03 23:08:47
【问题描述】:

我有以下输入:

int category;
int ID

ID是这样形成的数字:

//     CCXXXXNN
ID = 0x12345678;

而类别是介于 0x0 和 0xFF 之间的数字。

我想检查类别是否等于 ID 的 CC 部分。我该怎么做?如有必要,我可以将类别从 int 更改为 uint。

【问题讨论】:

    标签: c++ int hex


    【解决方案1】:

    您可以将您拥有的类别值左移到适当的位置,并将这些位与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.
    

    就我个人而言,我会为部件编写访问器函数并使用它们,因为它使事情更具可读性和灵活性,并且大大不易出错。
    根据我的经验,当你在玩弄游戏时,错误既容易犯错,也很难找到。

    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
    

    【讨论】:

      【解决方案2】:

      ID &amp; 0xff000000 == category &lt;&lt; 24

      【讨论】:

      • 不应该是24而不是6吗?
      • 我认为这两个答案都会受益于一些额外的解释。如果只是一堆没有任何评论或解释的代码(即使代码是正确的),我总是觉得很难对答案进行投票。
      【解决方案3】:
      (ID & 0xff000000) == (category << (6 * 4))
      

      【讨论】:

        【解决方案4】:

        实现它的另一种方法是使用联合:

        int category = 12;
        
        union u
        {
            int ID;
            struct a
            {
                BYTE dummy[3];
                BYTE category;
            } b;
        } ;
        
        u temp;
        
        if (temp.b.category == category)
        {
            // ...
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-27
          • 1970-01-01
          • 1970-01-01
          • 2011-05-19
          相关资源
          最近更新 更多