In computer science, a mask is data that is used for bitwise operations, particularly in a bit field.
Using a mask, multiple bits in a byte, nibble, word (etc.) can be set either on, off or inverted from on to off (or vice versa) in a single bitwise operation.
To turn certain bits on, the bitwise OR
operation can be used, following the principle that Y OR 1 = 1
and Y OR 0 = Y
. Therefore, to make sure a bit is on, OR
can be used with a 1
. To leave a bit unchanged, OR
is used with a 0
.
Example: Masking on the higher nibble (bits 4, 5, 6, 7) the lower nibble (bits 0, 1, 2, 3) unchanged.
More often, in practice, bits that are to be ignored are "masked off" (or masked to 0
) rather than "masked on" (or masked to 1
). There is no way to change a bit from on to off using the OR
operation. Instead, bitwise AND
is used. When a value is AND
ed with a 1
, the result is simply the original value, as in: Y AND 1 = Y
. However, AND
ing a value with 0
is guaranteed to return a 0
, so it is possible to turn a bit off by using AND
with 0
: Y AND 0 = 0
. To leave the other bits alone, use AND
with 1
.
Example: Masking off the higher nibble (bits 4, 5, 6, 7) the lower nibble (bits 0, 1, 2, 3) unchanged.
It is possible to use bitmasks to easily check the state of individual bits regardless of the other bits. To do this, turning off all the other bits using the bitwise AND
is done as discussed above and the value is compared with 0
. If it is equal to 0
, then the bit was off, but if the value is any other value, then the bit was on. What makes this convenient is that it is not necessary to figure out what the value actually is, just that it is not 0
.
Example: Querying the status of the 4th bit