Z80 assembly: Exchange and shadow registers
Swap register values quickly. Use the alternate register set as temporary storage.
EX exchanges two values. EXX swaps BC, DE and HL with an alternate set of registers. The alternate set is also called the shadow registers. It gives a program another set of working values.
These exchange instructions take 4 T-states. They do not change the flags. The Z80 has alternate AF, BC, DE and HL registers.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
EXX saves the first three pairs in the shadow set. The program uses BC in the new set, then EXX restores the original pairs. EX DE,HL swaps two 16-bit values.
Active registers and flags
Flags
Alternate flags
The full alternate pairs AF′, BC′, DE′ and HL′ appear in the register panel above. EXX swaps BC, DE and HL; EX AF,AF′ swaps A and F. The alternate set starts at 0 in this emulator. This page ignores undocumented X and Y bits.
Execution trace
| # | Address | Instruction | Result | T-states |
|---|
Exchange or copy?
| Instruction | Effect | Bytes | Time |
|---|---|---|---|
| EX DE,HL | Swap both pairs in one operation | 1 | 4 T |
| Three LD operations | Copy values into spare registers | At least 3 | At least 12 T |
| EXX | Swap all three register pairs with the shadow set | 1 | 4 T |
EXX makes it possible to save and restore BC, DE and HL together. No memory access is needed.
The alternate register set begins at zero. Interrupts and automatic register banking are not modeled.
Mnemonic glossary
Program mnemonics and directives
| Name | Stands for | Meaning here |
|---|---|---|
| LD | Load | Loads the initial values into registers. |
| EX | Exchange | Swaps the selected values. |
| EXX | Exchange register sets | Swaps BC, DE and HL with their alternate pairs. |
| HALT | Halt | Stops this lesson’s CPU. |
| ORG | Origin | Assembler directive. Sets the program address. |