如何使用位掩码 allow/disallow 操纵某些位

How to use bitmasks to allow/disallow manipulation of certain bits

我有一个代表 32 个独立状态的 32 位值。 我还有另一个 32 位值,它控制哪些位被锁定或可以被应用程序更改。

例如(为简洁起见使用 4 位掩码)

Example 1
Value          1010
Lock Mask      1000 - i.e. the 4th bit is locked, i.e. can't be altered
Incoming value 0100
New Result     1100 - 4th bit unchanged

Example 2
Value          0011
Lock Mask      1000 - i.e. the 4th bit is locked, i.e. can't be altered
Incoming value 1100
New Result     0100 - 4th bit unchanged

谁能解释一下我是如何做到这一点的。也许我需要更改掩码,以便它显示可以更改的位,即上面示例中的 0111...我不知道。

问候 马克.

假设一种类 C 语言,其中 & 是按位与; | 是按位或; ~ 是按位补码:

new_value = (value & locked) | (incoming & ~locked);

如果您觉得可读性更好,可以使用 + 代替 |