EX
Exchange, Block Transfer and Search Group
Expansion:
EXchange
Usage:
ex {rr}, {rr}
Limited to a shorter list of available combinations, the exchange instruction provides us with a way to swap values between two register pairs or values referenced by a pointer to a memory address.
| Instruction | Description | Opcode |
|---|---|---|
| EX AF, AF' | Swap values from AF registers with AF' shadow | 08 |
| EX DE, HL | Swap values between DE and HL register pairs | EB |
| EX (SP), HL | Swap 16-bit value in memory at address that we have in SP with the value in register HL | E3 |
| EX (SP), IX | Swap 16-bit value in memory at address that we have in SP with the value in register IX | DDE3 |
| EX (SP), IY | Swap 16-bit value in memory at address that we have in SP with the value in register IY | FDE3 |
Example
; Example
ld de, $1234 ; load the value $1234 into register pair DE
ld hl, $5678 ; load the value $5678 into register pair HL
ex de, hl ; exchange the contents of DE and HL
; After the EX instruction
; DE = $5678
; HL = $1234
Stack Pointer Memory location
; Example
ld sp, $FFFE ; set the stack pointer to address $FFFE
ld (sp), $1234 ; store the value $1234 at the address pointed to by SP
ld hl, $5678 ; load the value $5678 into register pair HL
ex (sp), hl ; exchange the contents of HL with the value at address SP
; after the EX instruction
; the value at address $FFFE = $5678
; HL = $1234
Shadow Register Swap
; Example
ld a, $55 ; load a value into the A register
ld f, $00 ; clear the flags register
ex af, af' ; exchange AF with AF'