0

Lets say I have a bitmask

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

So I already use 27 of my 32 available bits.

I now want to be able to also store and retrieve a 3 bit unsigned integer in addition to the flags using the bitmask.

For example:

// 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?

Basically I want to reserve 3 bits in my bitmask to save a number between 0-8 in there

Thank you for taking time to read and help.

4

1 回答 1

1

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

存储值:

mask |= val << 28;

要检索值:

val = mask >> 28;

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

val = (mask >> 28) & 0x0f;
于 2013-07-25T10:59:57.217 回答