Search code examples
maskboolean-logicbit

Replacing a bit range


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.