c00kiemonster
c00kiemonster

Reputation: 23351

How do I set a given bit from one bitmask to another in C?

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?

Upvotes: 2

Views: 165

Answers (2)

marbel82
marbel82

Reputation: 948

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

Upvotes: 1

Taylor Brandstetter
Taylor Brandstetter

Reputation: 3623

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.

Upvotes: 4

Related Questions