如何通过位掩码存储和检索3位数字



假设我有一个位掩码

enum ExampleMask
{       
   Attribute1 = 1 << 1,
   Attribute2 = 1 << 2,
   ...
   Attribute27 = 1 << 27
}

因此,我已经使用了32个可用位中的27个。

除了使用位掩码的标志之外,我现在还希望能够存储和检索一个3位无符号整数。

例如:

// Storing values
int mask =  Attribute2 | Attribute6 | Attribute18; // Saving some attributes
int mask |= ???? // How to save the number 8?
// Retrieving values
if(mask & Attribute2) do something...;
if(mask & Attribute6) do something...;
int storedValue =  ???? // How to retrieve the 8?

基本上,我想在我的比特掩码中保留3个比特,以在那里保存0-8之间的数字

感谢您抽出时间阅读并提供帮助。

您可以将值上移到未使用的位,例如

存储值:

mask |= val << 28;

检索值:

val = mask >> 28;

注意,mask实际上应该是unsigned,以避免在移位时传播符号位。如果由于某种原因必须使用带符号的int,那么在检索val时应该添加一个额外的屏蔽操作,例如

val = (mask >> 28) & 0x0f;

最新更新