CalculateQuestion 1 · Recall
Loading…
By the end you can use AND to test and clear bits, OR to set bits and XOR to flip bits, and write the mask needed to change exactly the bit you want.
Think of a mask as a stencil laid over a row of bits. Where the stencil has a hole, you see (or paint) the bit underneath; where it is solid, nothing gets through.
In computing the stencil is another bit pattern, and the operation combines it with ACC bit by bit. Each of the three bitwise operations does a different job:
| Operation | What it is good for | The mask bit that does the work |
|---|---|---|
AND |
testing a bit, and clearing bits | 1 keeps a bit, 0 clears it |
OR |
setting bits to 1 | 1 sets a bit, 0 leaves it alone |
XOR |
flipping bits | 1 flips a bit, 0 leaves it alone |
The operations work on all eight bits at once, independently. No carries, no borrowing — bit 3 cannot affect bit 4.
Truth tables for one bit
Everything follows from these three tiny tables. Read them as "ACC bit op mask bit".
| ACC bit | Mask bit | AND | OR | XOR |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
Two facts worth memorising:
AND with 0 always gives 0; AND with 1 gives back the original bit. That is why AND can test and clear."OR with 1 always gives 1; OR with 0 gives back the original bit. That is why OR can set."Worked example: Testing bit 3
ACC holds 0101 1010. Is bit 3 set? (Number the bits from 0 on the right, so bit 3 is the 8s column.)
To switch a bit on, OR it with a 1. Every other bit gets OR-ed with 0, which leaves it exactly as it was.
ACC holds 0101 1010 and you want bit 2 (the 4s column) set. Bit 2 is already 0, so:
ACC 0101 1010
mask 0000 0100
OR 0101 1110 (94)
If bit 2 had already been 1, the result would be identical — OR cannot tell the difference. That is a feature: setting something that is already set does no harm.
To switch a bit off, AND it with a 0. The rest of the mask is all 1s, so every other bit is preserved.
ACC holds 0101 1010 and you want bit 3 cleared:
ACC 0101 1010
mask 1111 0111 (247)
AND 0101 0010 (82)
The mask 1111 0111 is "all ones except bit 3" — the opposite of the mask you would use to test it. Working it out is easy: take the single-bit mask 0000 1000 and invert every bit.