使用位编码风格的位更新操作

Bit update operation using bit wise coding style

我想更新一点 5 位长的数据,而不管其他位的状态如何,即每一位都应该独立于 5 位长数据中的其他位。下面是我的代码。任何建议都会对我很有帮助。

case 35:
    AtemSwitcher.setTransitionNextTransition(0,(a=00001<<1));   
    break;
case 36:
    AtemSwitcher.setTransitionNextTransition(0,(b=00001<<2));
    break;
case 37:
    AtemSwitcher.setTransitionNextTransition(0,(c=00001<<3));
    break;
case 38:
    AtemSwitcher.setTransitionNextTransition(0,(d=00001<<4));
    break;

如果您只想对特定位进行操作,则需要使用 OR、AND 和 XOR 的掩码操作:

要设置一位,您需要使用按位或:

c = c | (1 << 4);
c |= 1 << 4; //set bit number 4
c |= (1 << 4) | (1 << 3); //set bit 4 and 3

要将某位设置为 0,您需要使用按位与:

c &= ~(1 << 4); //delete bit 4

您还需要 ~ 运算符的原因是,如果任何输入为 0,& 运算将为 0,因此您想将要清除的位设置为 0,以便它们将结果为0。

您还可以使用按位异或来切换位:

c ^= (1 << 4); //toggle bit 4