Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top