← r0mheat z80 lessons: all projects

Z80 assembly: Block copy and search

Copy bytes with LDIR. Find a byte with CPIR. Both instructions update pointers and a counter.

LDIR · LDDR · CPI · CPIR · CPD · CPDR

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.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

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

#AddressInstructionResultT-states

CPIR compared with CPI and JR NZ

; continue comparing while the byte differs
loop:  CPI
       JR NZ,loop
Search controlBytesContinuing passLast pass
CPIR221 T16 T
CPI + JR NZ428 T23 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
NameStands forMeaning here
LDLoadLoads address and byte count into register pairs.
LDIRLoad, Increment, RepeatCopies one byte, moves HL and DE forward, and repeats until BC is 0.
CPIRCompare, Increment, RepeatCompares A with each byte until it matches or BC reaches 0.
DBDefine ByteAssembler directive. Places source bytes in memory.
DSDefine SpaceAssembler directive. Reserves destination bytes.
HALTHaltStops after the search.