位的合理比较

Rational comparison of bits

我有多个int类型。它位于 [0,255] 范围内。即,包括8位。我需要经常检查说:

2(整数) = 00000010(二进制)

  1. The bit 6 and bit 7 must be equal to 0 and 1 respectively. 
  And I check it like this:
if ((!(informationOctet_ & (1 << 6))) && (informationOctet_ & (1 << 7)))
{
    ...
}

但是可读性不是很好,是否可以-做点什么"beautiful"? 我不能用 std::bitset,我的头说这是浪费资源,你不能没有它。

您可以应用一些掩蔽技术,

int i = 246; // Lets say any value.
int chk = ( i & 00000110b ); // eliminates all other bits except 6th & 7th bit
if (chk == 2) // because we want to check 6th bit is 0 & 7th is 1, that becomes 2 value in decimal
    printf("The 6th bit is 0 & 7th bit is 1");
else
    printf("Either 6th bit is not 0 or 7th bit is not 1, or both are not 0 & 1 respectivly");

有两种合理的解决方案:要么将所有无关位设置为零,然后测试结果,要么将无关位设置为 1 并测试结果:

(x & 0xC0) == 0x80
(x | ~0xC0) == ~0x40

正如哈罗德在评论中指出的那样,第一种形式更为常见。这种模式很常见,编译器的优化器会识别它。

存在其他形式,但它们晦涩难懂:((x ^ 0x80) & 0xC0 == 0) 也同样有效,但不太清楚。一些 ISA 不能直接加载大常量,所以它们使用 ((x>>6) & 0x3) == 0x2 的等价物。不要为这个烦恼,你的优化器会。