Z80 assembly: DJNZ
The counted loop. One instruction decrements B and jumps back until B reaches zero.
- B ← B − 1
- if B ≠ 0: PC ← PC + e (jump, 13 T-states)
- if B = 0: continue (8 T-states)
- flags: none change
The second byte, e, is a signed displacement. It is added to the address after DJNZ. Here, FCh (−4) at 0106h gives 0108h − 4 = 0104h.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
The loop adds 3 to A once per pass. Registers start at 0. The highlighted row is at PC. Each Step executes one instruction fetched from memory.
Registers and flags
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.
Execution trace
| # | Address | Instruction | Result | T-states |
|---|
DJNZ compared with two instructions
; use B as the loop counter
loop: DEC B
JR NZ,loop
| Loop control | DJNZ | DEC B + JR NZ |
|---|
DEC B changes S, Z, H, P/V and N. DJNZ changes no flags. The timing counts here cover loop control only.
Mnemonic glossary
Program mnemonics
| Mnemonic | Stands for | What it does here |
|---|---|---|
| LD | Load | Loads a value into a register. |
| ADD | Add | Adds 3 to A and updates all six documented flags. |
| DJNZ | Decrement B, Jump if Not Zero | Subtracts 1 from B. It jumps back if B is not 0. It does not change flags. |
| HALT | Halt | Stops this lesson’s CPU until reset. Interrupts are not modeled. |
| ORG | Origin | Assembler directive, not a CPU instruction. Places the COM-style program at 0100h. |