Masking
It is often useful to examine the state of certain bits (such as the status of a peripheral chip or a flag). We are interested in the state of a given bit, but the state of the other bits is unknown (and unimportant to us).
For example, assume we want to check the state of bit 0 in a byte that has been read from a status register. To do this, we need to compare the byte with a constant. But what constant should we choose? In both the following examples of a byte read from a status register, bit 0 is set. Comparing the byte with the constant 0x65 will work in the first instance but not the second:
0 1 1 0 0 1 0 1 (0x65) 1 1 0 0 1 1 0 1 (0xCD)
There is no single number with which we can compare the byte that will work in all instances. We need to set all the other bits to a known state before we can do a comparison. To do this, it is necessary to mask out any bits in which we are not interested. This may be accomplished by using an AND instruction.
In the previous example, we need to AND the byte from the status register with 0x01 to clear the other bits. This will preserve bit 0 (regardless of its state) and clear all other bits. The result of this operation is 0x01 if bit 0 was set or 0x00 if bit 0 was clear:
0 1 1 0 0 1 0 1 (0x65) 0 0 0 0 0 0 0 1 (0x01) AND
This gives:
0 0 0 0 0 0 0 1 (0x01)
The following operation:
1 1 0 0 1 1 0 1 (0xCD) 0 0 0 0 0 0 0 1 (0x01) AND
gives:
0 0 0 0 0 0 0 1 (0x01)
Finally, this operation:
1 0 0 0 1 1 0 0 (0x8C) 0 0 0 0 0 0 0 1 (0x01) AND
gives:
0 0 0 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access