Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top