Z80 assembly: Strings, fast fill and copy
A string is a sequence of character bytes. Fill a memory range, then copy a string with LDIR.
A string is stored as one byte per character. This example uses ASCII bytes for “Z80!”. A fill loop writes the same value to several addresses. LDIR copies a block forward and updates HL, DE and BC after each byte.
The fill loop takes 26 T-states for each continuing byte and 21 for the last. LDIR takes 21 T-states while repeating and 16 on its last byte.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
The program fills 011Bh–011Eh with 2Ah. Then it copies the four bytes at 0117h–011Ah to 011Fh–0122h.
Registers and memory
Flags
ASCII assigns a number to each character. Z is 5Ah, 8 is 38h, 0 is 30h, and ! is 21h. The bytes are not stored as special string objects.
Source, fill and copy areas
Execution trace
| # | Address | Instruction | Result | T-states |
|---|
Block instruction or manual loop?
| Task | Code | Continuing byte | Last byte |
|---|---|---|---|
| LDIR copy | 2 bytes | 21 T | 16 T |
| LD A,(HL) + LD (DE),A + pointer updates + branch | 7 bytes | 44 T | 39 T |
| Fill loop: LD (HL),A + INC HL + DJNZ | 4 bytes | 26 T | 21 T |
LDIR copies from a source range. It cannot repeat one source byte to fill a range, because HL moves after each copy. Use a fill loop for repeated values.
The string has a fixed length of four bytes and no zero terminator. Real programs can use a terminator or a separate length value.
Mnemonic glossary
Program mnemonics and directives
| Name | Stands for | Meaning here |
|---|---|---|
| LD | Load | Sets up values and writes fill bytes. |
| INC | Increment | Moves HL to the next memory byte. |
| DJNZ | Decrement B and Jump if Not Zero | Repeats the fill loop four times. |
| LDIR | Load, Increment, Repeat | Copies the string bytes forward. |
| DB | Define Byte | Assembler directive. Stores the string bytes. |
| DS | Define Space | Assembler directive. Reserves fill and copy ranges. |
| HALT | Halt | Stops after the copy. |