位数学 - 在单个操作中将 2 个相反的位(10 或 01)分配给一个数字,无论原始数字是什么

Bit Math - Assigning 2 opposite bits (10 or 01) to a number in a single operation no matter what the original number is

假设我有一个二进制数X。是否可以在单个操作中将数字中的 2 位设置为 1001 X 的值无关

这对于单个位是可能的。我可以设置位 10 无论原始号码使用什么:

x |= (1 << bit_position) // Ensures bit at bit_position is 1 always.

x &= ~(1 << bit_position) // Ensures bit at bit_position is 0 always.

我对此进行扩展以设置 2 位,它们是 1100。但是有没有一种操作可以让我在一次操作中将它们设置为 1001,而不依赖于 X 的值?

x ??= ??(0b01 << bit_position)

??是我想不通的部分。

请注意,我不想切换位。只需将相关的设置为 0110.

虽然它不会有那种形式。您必须屏蔽掉一个字节中要更改的位和另一个字节中要保留的位。

// put 0 in bit 2 and 1 in bit 3

byte mask = 0b00001100;  // The bits I want to play with
byte pattern = 0b00001000;  // doesn't matter what any bit but 2 and 3 are

someByte = ((pattern & mask) | (somebyte & ~mask));

还有更通用的方式

uint32_t SetBits(uint32_t InitialValue, uint32_t pattern, int pos, int nbits)
{
 uint32_t mask = (((1 << nbits) - 1) << pos); 
 InitialValue &= ~mask;
 return InitialValue | (pattern & mask)
}

或单次操作:

return (InitialValue & ~(((1 << nbits) - 1) << pos)) | (pattern & (((1 << nbits) - 1) << pos))

您无需担心此公式中出现多重掩码计算。编译器只会计算一次。