cbit-manipulationbitmaskansi-c

Merge two bitfields according a bitmask


I wondering whether is it possible to use bit operations to merge two bitfields according a bitmask? For example I have two values, and a bitmask:

char mask = 0x29; // 0010 1001
char a = 0x9;     // 0000 1001 original value
char b = 0xE8;    // 1110 1000 modified value

And I want to set the bits in b to the value of a, according the bitmask. Only 3 bits would be affected.

char val = 0xC9;  // 1100 1001 value

So how can I do with only bit operations?

Thanks in advance.


Solution

  • First, clear off the bits that are set in the mask from b. Then, clear off the bits that are not set in the mask from a. Finally, OR the two results together:

    b = (b & ~mask) | (a & mask);
    

    The tilde ~ operator produces the negated mask. ANDing with ~mask zeroes out the bits of b that are set in the mask.