← r0mheat z80 lessons: all projects

Z80 assembly: Comparing and jumping

Compare bytes in a table. A conditional jump changes the next address when a flag matches.

CP · JP · JR

CP compares A with a value by subtracting it for the flags. A stays unchanged. JP jumps to a full 16-bit address. JR jumps by a signed 8-bit offset. Both can test conditions such as Z, NZ, C and NC.

CP A,n takes 7 T-states. JP nn takes 10. JR takes 12 when taken and 7 when not taken. DJNZ takes 13 when taken and 8 when B reaches zero.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

The program checks three bytes at 0114h–0116h for 2Ah. The matching byte is at 0115h. Step through CP, JP Z and the loop branches.

Registers, flags and table bytes

Flags

CP changes flags as subtraction would, but keeps A unchanged. Z is set when the compared values are equal. This page ignores undocumented X and Y bits.

Table data at 0114h

Execution trace

#AddressInstructionResultT-states

Compare the loop forms

MethodBytesTimeFlags
DJNZ loop2 bytes13 T taken; 8 T finalunchanged
DEC B + JR NZ3 bytes16 T taken; 11 T finalDEC changes flags

The comparison is for loop control only. The search also uses CP and branches to the match or finish address.

The program scans a fixed three-byte table. It does not read input or use interrupts. JP and JR use the documented Z80 flag conditions.

Mnemonic glossary

Program mnemonics and directives
NameStands forMeaning here
LDLoadLoads the table address and loop count.
CPCompareSubtracts for flags without changing A.
JPJumpLoads a full address into PC when its condition is true.
JRJump RelativeAdds a signed offset to the next instruction address.
DJNZDecrement B and Jump if Not ZeroCounts table entries.
DBDefine ByteAssembler directive. Places table bytes in memory.
HALTHaltStops this lesson’s CPU.