CIE AS & A Level Computer Science, section 4.3 (Bit manipulation)
Bit masking
A mask is a binary number used with a logical operation to affect chosen bits. The assembly instructions AND, OR and XOR work on the ACC and an operand.
The four operations
Take the byte .
| Task | Operation | Mask | Result |
|---|---|---|---|
| Test bit 1 | AND |
(non-zero, so bit 1 is set) | |
| Set bit 3 to 1 | OR |
||
| Clear bit 4 to 0 | AND |
||
| Toggle bit 7 | XOR |
- AND with a 1 keeps a bit, and with a 0 clears it.
- OR with a 1 sets a bit, and with a 0 leaves it.
- XOR with a 1 flips a bit, and with a 0 leaves it.
Bits are numbered from 0 at the right.
Monitoring and controlling a device
A byte can be used as a control or status register for a device, with each bit a separate switch or sensor.
| Bit | Meaning |
|---|---|
| 0 | motor on |
| 1 | door closed (sensor) |
| 2 | alarm on |
- To check the door sensor:
AND B00000010and test whether the result is zero. - To switch the alarm on:
OR B00000100. - To switch the motor off:
AND B11111110.
Common mistake: using the wrong operation or mask. To clear a bit use AND with a mask that has 0 in that position and 1 everywhere else. To set a bit use OR with a 1 in that position. Remember to count bits from 0 on the right.
Exam tip: write the byte and the mask one above the other, and apply the operation bit by bit. Say which operation you use for test, set, clear or toggle.
Check yourself
Which operation and mask sets bit 0 of a byte?
OR with .
Apply AND with to .
.
Which operation toggles a bit?
XOR with a mask having 1 in that bit position.