【问题标题】:Rational comparison of bits位的合理比较
【发布时间】:2015-01-30 08:14:05
【问题描述】:

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

2(int) = 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)))
{
    ...
}

但它的可读性不是很高,是否有可能——做一些“漂亮”的事情? 我不能使用 std::bitset,我的脑袋说这是浪费资源,你不能没有它。

【问题讨论】:

  • (x &amp; 0xC0) == 0x80(即通常的方式)不够好吗?

标签: c++11 int bit-manipulation bit


【解决方案1】:

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

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

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

存在其他形式,但它们是模糊的:((x ^ 0x80) &amp; 0xC0 == 0) 也可以工作,但不太清楚。一些 ISA 不能直接加载大常量,所以它们使用 ((x&gt;&gt;6) &amp; 0x3) == 0x2 的等价物。不用担心这个,你的优化器会的。

【讨论】:

    【解决方案2】:

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

    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");
    

    【讨论】:

    • 通常位编号为 LSB (0) 到 MSB (7)。此外,据我所知,二进制文字是 c++14 context
    • 类似地,如果您说位的编号是从 0 到 7。然后通过将掩码更改为 00000011b 并将结果与​​十进制的 1 进行比较,您也可以找出答案。但是技术是一样的。
    • @WaqasShabbir:MSB 表示 most 有效位,最左边。 0b00000011 设置了最右边的 LSB,即位 0。
    猜你喜欢
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多