Search code examples
bitbitmask

How to use bitmasks to allow/disallow manipulation of certain bits


I have a 32 bit value which represents 32 individual states. I also have another 32 bit value which controls which bits are either locked or can be altered by an application.

For instance ( using a 4 bit mask for succinctness )

Example 1
Value          1010
Lock Mask      1000 - i.e. the 4th bit is locked, i.e. can't be altered
Incoming value 0100
New Result     1100 - 4th bit unchanged

Example 2
Value          0011
Lock Mask      1000 - i.e. the 4th bit is locked, i.e. can't be altered
Incoming value 1100
New Result     0100 - 4th bit unchanged

Can someone kindly explain how I could achieve this. Maybe I need to change the mask so that it show bits that can be changed, i.e. 0111 in the above example... I don't know.

Regards Mark.


Solution

  • Assuming a C-like language where & is bitwise-and; | is bitwise-or; and ~ is bitwise-complement:

    new_value = (value & locked) | (incoming & ~locked);
    

    You could use + instead of |, if you felt it was more readable.