Z80 assembly: Arithmetic and flags

Add and subtract numbers. See how the result changes the Z80 flags.

ADD · SUB · INC · DEC

ADD adds. SUB subtracts. INC adds 1. DEC subtracts 1. A flag is a one-bit record of a result, such as zero, sign, half-carry, overflow, or carry.

Register forms usually take 4 T-states. Immediate forms take 7. INC and DEC take 4. ADD HL,rr takes 11. T-states are CPU clock periods.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

The program first adds 1 to 7Fh. This crosses from positive to negative in signed 8-bit arithmetic. It then subtracts 80h and adds 0100h to HL.

Registers and flags

Flags

S is sign. Z is zero. H is half-carry between bits 3 and 4. P/V is parity or signed overflow. N marks subtraction. C is carry or borrow. This page ignores undocumented X and Y bits.

Program bytes

Execution trace

#AddressInstructionResultT-states

Compare the arithmetic forms

InstructionOperationFlags changedTime
ADD A,BAdd B to AS, Z, H, P/V, N, C4 T
ADD A,nAdd an immediate byteS, Z, H, P/V, N, C7 T
INC AAdd 1 to AS, Z, H, P/V, N; C preserved4 T
ADD HL,DEAdd DE to HLH, N, C; S, Z, P/V preserved11 T

INC and DEC leave carry unchanged. The 16-bit ADD HL,DE also keeps S, Z and P/V unchanged.

The examples treat bytes as unsigned for carry and also show the signed overflow flag. Memory is flat. Interrupts are not modeled.

Mnemonic glossary

Program mnemonics and directives
NameStands forMeaning here
LDLoadCopies a value into a register.
ADDAddAdds two values.
INCIncrementAdds 1.
DECDecrementSubtracts 1.
SUBSubtractSubtracts a value from A.
HALTHaltStops this lesson’s CPU.
ORGOriginAssembler directive. Sets the program address.