Replacing a bit range
-
03-07-2019 - |
Question
Something any sophomore in CS should be able to answer, but I can't seem to wrap my head around it...
I have a set of bits, and I need to replace some of the bits with a different set. In a simplified example:
10101010 -original bit set
00001111 -mask showing replacement positions
00001100 -new bit values
10101100 -resulting bit set
Another example:
10101010 -original bit set
00110011 -mask
11111111 -new bit values
10111011 -resulting bit set
It's trivial to do this by iterating across the bits.
Is it possible to do this using boolean logic (AND, OR, etc.)?
Solution
result = (original & ~mask) | (newbits & mask)
The "& ~mask" part make sure to clear those bits to 0 before the | part.
The "& mask" part make sure that only proper bits in newbits are used.
OTHER TIPS
(NEW and MASK) OR (OLD and NOT MASK)
Mask out the bits to be replaced out of the original (by ANDing with the NOT of the mask), then put the new bits in (via OR).
10101010 -original bit set
00001111 -mask showing replacement positions
00001100 -new bit values
11110000 -negated mask
10100000 -original bitset masked
10101100 -new bits put back in
In C(++) code, it would be:
out = (in & ~mask) | newbits;
If the newbits contain bits outside of what they're supposed to replace, AND them with the mask as well.