Question

Apologies up front as I somehow feel this question is trivial, but I can't seem to get my head around it and the answers I found online seem to be only concerned with setting and resetting single bits.

I have a 32bit number that I am using to store several fields of information. The way this is done is to define various offsets and masks, e.g.

uint32_t          key_;
static const uint16_t offset_  = 10; // example field, key uses all 32 bits
static const uint16_t mask_    = 0x1FF;

setting is done in a method as in:

void setField( unsigned int rhs ) { key_ |= ( rhs << offset_ ); } 

or extracted

unsigned int getField() { return ( key_ >> offset_ ) & mask_; }

All of this is fine, provided that I never need to set a new value in the field in question. If I do set a new value, I need to first erase all the bits for this field (and only those), since of course:

key |=  10 << offset_; // followed by
key |=  16 << offset_;

key_ >> offset_ & mask_; // = 26 and not 16

Now, what I am looking for is a way to first reset the field in the setter method so as to assure that only the last value will be taken, but the only thing that I could come up with is something like:

key_ ^= ( key_ >> offset_ & mask_ ) << offset_;

so get the current value from the key and XOR it with the complete key so as to set all those bits to zero. Now, this works, but seems convoluted for such a seemingly simple task.

Any hints on how this can be done more efficiently or elegantly would be gladly appreciated.

Was it helpful?

Solution

It is quite easy to turn off bits of a given mask:

key_ &= ~(mask);

Now all bits set in mask will be turned off and the rest of the bits are intact. I believe knowing that you will be able to perform what you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top