Z80 assembly: Block copy and search
Copy bytes with LDIR. Find a byte with CPIR. Both instructions update pointers and a counter.
LDIR copies forward and repeats. LDDR copies backward. CPI compares A with the byte at HL and moves forward. CPIR repeats that search. CPD and CPDR move backward. BC counts bytes. HL points to the current source or search byte. DE points to the copy destination.
LDIR and LDDR take 21 T-states while repeating, then 16 on the last byte. CPIR and CPDR take 21 while continuing and 16 when they find a match or BC reaches 0. LDI, LDD, CPI and CPD take 16.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
The program copies three bytes from 0116h to 0119h. Then CPIR searches the source at 0116h for 2Ah. The match is at 0117h.
Registers and memory
Flags
P/V is 1 while BC is not zero. For CPIR, Z is 1 when A matches the byte. Carry is preserved by these instructions. This page ignores undocumented X and Y bits.
Source, destination and search data
Execution trace
| # | Address | Instruction | Result | T-states |
|---|
CPIR compared with CPI and JR NZ
; continue comparing while the byte differs
loop: CPI
JR NZ,loop| Search control | Bytes | Continuing pass | Last pass |
|---|---|---|---|
| CPIR | 2 | 21 T | 16 T |
| CPI + JR NZ | 4 | 28 T | 23 T |
The table counts the search instruction and its branch. Both versions compare the same bytes and update HL and BC.
The emulator uses a flat 64 KB memory. It does not model memory wait states or interrupts during a block instruction.
Mnemonic glossary
Program mnemonics and directives
| Name | Stands for | Meaning here |
|---|---|---|
| LD | Load | Loads address and byte count into register pairs. |
| LDIR | Load, Increment, Repeat | Copies one byte, moves HL and DE forward, and repeats until BC is 0. |
| CPIR | Compare, Increment, Repeat | Compares A with each byte until it matches or BC reaches 0. |
| DB | Define Byte | Assembler directive. Places source bytes in memory. |
| DS | Define Space | Assembler directive. Reserves destination bytes. |
| HALT | Halt | Stops after the search. |