Question

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.

Was it helpful?

Solution

You can just shift the value up into the unused bits, e.g.

To store the value:

mask |= val << 28;

To retrieve the value:

val = mask >> 28;

Note that mask should really be unsigned to avoid propagating the sign bit when shifting. If you have to use a signed int for some reason then you should add an additional masking operation when retrieving val, e.g.

val = (mask >> 28) & 0x0f;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top