Z80 assembly: Exchange and shadow registers

Swap register values quickly. Use the alternate register set as temporary storage.

EX DE,HL · EX AF,AF′ · EXX

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.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

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

#AddressInstructionResultT-states

Exchange or copy?

InstructionEffectBytesTime
EX DE,HLSwap both pairs in one operation14 T
Three LD operationsCopy values into spare registersAt least 3At least 12 T
EXXSwap all three register pairs with the shadow set14 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
NameStands forMeaning here
LDLoadLoads the initial values into registers.
EXExchangeSwaps the selected values.
EXXExchange register setsSwaps BC, DE and HL with their alternate pairs.
HALTHaltStops this lesson’s CPU.
ORGOriginAssembler directive. Sets the program address.