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?

有帮助吗?

解决方案

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.

其他提示

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).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top