【发布时间】:2014-02-03 23:08:47
【问题描述】:
我有以下输入:
int category;
int ID
ID是这样形成的数字:
// CCXXXXNN
ID = 0x12345678;
而类别是介于 0x0 和 0xFF 之间的数字。
我想检查类别是否等于 ID 的 CC 部分。我该怎么做?如有必要,我可以将类别从 int 更改为 uint。
【问题讨论】:
我有以下输入:
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.
就我个人而言,我会为部件编写访问器函数并使用它们,因为它使事情更具可读性和灵活性,并且大大不易出错。
根据我的经验,当你在玩弄游戏时,错误既容易犯错,也很难找到。
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
【讨论】:
ID & 0xff000000 == category << 24
【讨论】:
(ID & 0xff000000) == (category << (6 * 4))
【讨论】:
实现它的另一种方法是使用联合:
int category = 12;
union u
{
int ID;
struct a
{
BYTE dummy[3];
BYTE category;
} b;
} ;
u temp;
if (temp.b.category == category)
{
// ...
}
【讨论】: