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.

xNidhogg
  • 331
  • 1
  • 4
  • 12

1 Answers1

1

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;
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • `mask` and `val` are signed though. Shouldn't they be unsigned integers in order to avoid UB? – Nikos C. Jul 25 '13 at 11:02
  • You'd also need to change the type to `unsigned` (or, more portably, `uint32_t`). – Mike Seymour Jul 25 '13 at 11:02
  • I was just editing the answer to cover the issue with signed int - for a 3 bit value it doesn't matter but it appears the OP actually wants 4 bits so I've added a note about masking or using unsigned int. – Paul R Jul 25 '13 at 11:04
  • `val = mask >> 28` can be a problem if there are even more bits beyond the three (or four) relevant bits. I would suggest to use `val = (mask >> 28) % 8`, or: `val = (mask >> Attribute28) % (1<<3)` – MyPasswordIsLasercats Jul 25 '13 at 11:05