Z80 assembly: Logic and bits
Use masks to keep, clear, or toggle bits. Test one bit without changing the value.
AND keeps bits set in both values. OR sets a bit if either value has it. XOR sets a bit when the values differ. BIT tests a bit. SET makes it 1. RES makes it 0.
AND, OR and XOR update S, Z, H, P/V, N and C. BIT updates S, Z, H and P/V, while preserving C. SET and RES do not change flags.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
The program starts with 11001100b. It combines masks, tests bit 7, clears it, then sets bit 0.
Registers, flags and program bytes
Flags
A mask is a value used to select bits. In this example, 0Fh keeps the low nibble. 80h selects bit 7. BIT sets Z when the tested bit is 0, sets H, clears N and preserves C. This page ignores undocumented X and Y bits.
Program memory
Execution trace
| # | Address | Instruction | Result | T-states |
|---|
Bit operation effects
| Instruction | Input A | Other value / bit | Output A |
|---|---|---|---|
| AND 0Fh | CCh | 0Fh | 0Ch |
| OR 80h | 0Ch | 80h | 8Ch |
| XOR 0Ch | 8Ch | 0Ch | 80h |
| RES 7,A | 80h | bit 7 | 00h |
| SET 0,A | 00h | bit 0 | 01h |
AND with 0Fh is one way to keep only the low four bits. OR with 80h sets the top bit.
The examples use register A. The same bit instructions can also operate on the byte at (HL). Input/output ports and interrupts are not modeled.
Mnemonic glossary
Program mnemonics and directives
| Name | Stands for | Meaning here |
|---|---|---|
| LD | Load | Loads the first byte into A. |
| AND | Logical AND | Keeps bits set in both inputs. |
| OR | Logical OR | Sets bits present in either input. |
| XOR | Exclusive OR | Sets bits that differ. |
| BIT | Bit test | Tests one bit without changing A. |
| SET | Set bit | Changes the selected bit to 1. |
| RES | Reset bit | Changes the selected bit to 0. |
| HALT | Halt | Stops this lesson’s CPU. |