Z80 assembly: LDIR

One instruction copies a block of memory. Step through it and watch HL, DE and BC change.

LDIREDB0Load, increment, repeat
  • (DE) ← (HL); HL ← HL + 1; DE ← DE + 1
  • BC ← BC − 1
  • if BC ≠ 0: repeat; else continue
  • 21 T-states per repeated transfer; 16 on the last
  • H = 0, N = 0, P/V = 1 while BC ≠ 0; S, Z, C unchanged
Bytes to copy
Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

ORG 0100h marks the entry address. The 12 code bytes end at 010Ch. DB places the source string there; DS reserves the destination immediately after it. The highlighted row is at PC.

Registers, flags and memory

Flags

A register is a small storage place in the CPU. PC means Program Counter. A T-state is one CPU clock period. A flag records a result from an instruction. S is sign, Z is zero, H is half-carry, P/V is parity or overflow, N is add/subtract, and C is carry. This page ignores undocumented X and Y bits.

Source memory HL points to the next byte

Destination memory DE points to the next byte

Execution trace

#AddressInstructionResultT-states

LDIR compared with a manual copy loop

loop:  LD A,(HL)   ; read source
       LD (DE),A   ; write destination
       INC HL
       INC DE
       DEC BC
       LD A,B
       OR C
       JR NZ,loop
For bytesLDIRManual loop

The table counts loop instructions only. Both programs also use 30 T-states to load registers before copying. The code-size row counts only the copy instruction or loop body.

Simplification: memory is a flat 64 KB array. Interrupts and the repeated refresh cycles during HALT are outside this lesson.

Mnemonic glossary

Program mnemonics and directives
NameStands forWhat it does here
LDLoadLoads the source address, destination address, or byte count.
LDIRLoad, increment, repeatCopies one byte, advances HL and DE, and decreases BC.
HALTHaltStops this lesson’s CPU. Interrupts are not modeled.
ORGOriginAssembler directive, not a CPU instruction. Sets the code address.
DBDefine ByteAssembler directive, not a CPU instruction. Places source bytes in memory.
DSDefine SpaceAssembler directive, not a CPU instruction. Reserves destination bytes.