# `ex`

[Z80 Documentation](https://asm-editor.specy.app/documentation/z80.md) › [Instructions](https://asm-editor.specy.app/documentation/z80/instruction.md)

Web page: https://asm-editor.specy.app/documentation/z80/instruction/ex

**Exchange**

Category: Data movement

Swaps AF with AF', DE with HL, or the word at (SP) with HL, IX or IY.

Used in: [Multiply and divide, with the remainder](https://asm-editor.specy.app/learn/courses/z80/examples/multiply-and-divide.md) (Z80 assembly), [Print a number in any base without help](https://asm-editor.specy.app/learn/courses/z80/examples/number-to-string.md) (Z80 assembly), [Flappy bird](https://asm-editor.specy.app/learn/courses/z80/examples/flappy-bird.md) (Z80 assembly)

## Flags

| Flag | Effect |
| --- | --- |
| S | not changed |
| Z | not changed |
| H | not changed |
| P/V | not changed |
| N | not changed |
| C | not changed |

## Forms

- `ex af, af'` · 1 byte · 4 cycles · Exchanges the 16-bit contents of AF and AF'.

- `ex (sp), hl` · 1 byte · 19 cycles · Exchanges (SP) with L, and (SP+1) with H.

- `ex de, hl` · 1 byte · 4 cycles · Exchanges the 16-bit contents of DE and HL.

- `ex (sp), ix` · 2 bytes · 23 cycles · Exchanges (SP) with IXL, and (SP+1) with IXH.
  - `ex (sp), ix`
  - `ex (sp), iy`

## Pseudo-instructions

Other spellings the assembler accepts; each form shows the instruction it becomes.

- `ex af', af` · 1 byte · 4 cycles · Exchanges the 16-bit contents of AF and AF'.
  - `ex af', af` → `ex af, af'`

- `ex hl, (sp)` · 1 byte · 19 cycles · Exchanges (SP) with L, and (SP+1) with H.
  - `ex hl, (sp)` → `ex (sp), hl`

- `ex hl, de` · 1 byte · 4 cycles · Exchanges the 16-bit contents of DE and HL.
  - `ex hl, de` → `ex de, hl`

- `ex ix, (sp)` · 2 bytes · 23 cycles · Exchanges (SP) with IXL, and (SP+1) with IXH.
  - `ex ix, (sp)` → `ex (sp), ix`
  - `ex iy, (sp)` → `ex (sp), iy`

## Operands

- [`ix`](https://asm-editor.specy.app/documentation/z80/registers/register-ix.md): The `ix` index register. You can also use `iy`, with the same instruction size and timing.

## Example

```z80
        .org 0x8000
        ld a, 5
        ex af, af'
        halt
```
