Z80 assembly: Arithmetic and flags
Add and subtract numbers. See how the result changes the Z80 flags.
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.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
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
| # | Address | Instruction | Result | T-states |
|---|
Compare the arithmetic forms
| Instruction | Operation | Flags changed | Time |
|---|---|---|---|
| ADD A,B | Add B to A | S, Z, H, P/V, N, C | 4 T |
| ADD A,n | Add an immediate byte | S, Z, H, P/V, N, C | 7 T |
| INC A | Add 1 to A | S, Z, H, P/V, N; C preserved | 4 T |
| ADD HL,DE | Add DE to HL | H, N, C; S, Z, P/V preserved | 11 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
| Name | Stands for | Meaning here |
|---|---|---|
| LD | Load | Copies a value into a register. |
| ADD | Add | Adds two values. |
| INC | Increment | Adds 1. |
| DEC | Decrement | Subtracts 1. |
| SUB | Subtract | Subtracts a value from A. |
| HALT | Halt | Stops this lesson’s CPU. |
| ORG | Origin | Assembler directive. Sets the program address. |