|
Used to calculate AND bitmask
Wikipedia:
https://en.m.wikipedia.org/wiki/Mask_(computing)
Masking bits to 0
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 ANDed with a 1, the result is simply the original value, as in: Y AND 1 = Y. However, ANDing 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.
10010101 10100101
AND 00001111 00001111
-----------------
= 00000101 00000101
Querying the status of a bit
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 1. 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
10 01 11 01 10 01 01 01
AND 00001000 00001000
----------------------
= 00001000 00000000
|