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.
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 froma. Finally,ORthe two results together:The tilde
~operator produces the negated mask.ANDing with~maskzeroes out the bits ofbthat are set in the mask.