What is Bit Masking?

VietMX Staff asked 3 years ago

mask (or bitmask) defines which bits you want to keep, and which bits you want to clear. Using a mask, multiple bits in a byte can be set either on, off or inverted from on to off (or vice versa) in a single bitwise operation.

This is accomplished by doing:

  • Bitwise ANDing in order to extract a subset of the bits in the value
       1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
/* ---------------------------_-*/
       0 0 1 0 1 1 0 0  [output]
  • Bitwise ORing in order to set a subset of the bits in the value
       1 1 1 0 1 1 0 1   [input]
(|)  0 0 1 1 1 1 0 0    [mask]
/* ---------------------------_-*/
       1 1 1 1 1 1 0 1  [output]
  • Bitwise XORing in order to toggle a subset of the bits in the value
       1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
/*------------------------------*/
       1 1 0 1 0 0 0 1  [output]

Using bitmask we can:

  • easily check the state of individual bits regardless of the other bits:
       1 0 0 1 1 1 0 1   [input]
(&)  0 0 0 0 1 0 0 0    [mask]
/*------------------------------*/
       0 0 0 0 1 0 0 0  [output]
  • Toggling bit values. This can be achieved using the XOR (exclusive or) operation.
       1 0 0 0 1 1 0 1   [input]
(^)  0 0 0 0 1 1 1 1    [mask]
/*------------------------------*/
       1 0 0 1 0 0 1 0  [output]