Question

I want to set a given bit from one bitmask to another in C. This is the way I do it currently.

const int MASK_THIRD = (1<<2);

if (mask & MASK_THIRD) {
    mask_another |= MASK_THIRD;
} else {
    mask_another &= ~MASK_THIRD;
}

Is there a smarter way of doing it?

Was it helpful?

Solution

Another way:

mask_another ^= ((mask ^ mask_another) & MASK_THIRD);

Which is in essence saying "if the bit is different, flip it". It requires one less operation which is why I figured it's worth mentioning.

OTHER TIPS

mask_another = (mask_another & (~MASK_THIRD)) | (mask & MASK_THIRD);

Reset bit in mask_another (mask_another & (~MASK_THIRD)) and combine it with bit from mask (mask & MASK_THIRD).

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