Arithmetic with Carry: ADC and SBC

When adding numbers larger than 8 bits (like a 16-bit word or a 32-bit integer), you must add the Carry flag (C) from the previous operation into the current one. This is done with the ADC and SBC instructions.

The Principle: Add (or Subtract) the current byte PLUS the Carry flag.

Instruction Action Purpose
ADC A, R A ← A + R + C Add with Carry: Used to link the result of the previous 8-bit addition.
SBC A, R A ← A - R - C Subtract with Carry/Borrow: Used to link the result of the previous 8-bit subtraction.

Example: 16-bit Addition (BC + DE)

We add the low bytes first, then the high bytes, including the carry from the low byte.

    LD   A, C             ; Load Low Byte 1
    ADD  A, E             ; Add Low Byte 2 (result and carry into A/C)
    LD   C, A             ; Store new Low Byte in C

    LD   A, B             ; Load High Byte 1
    ADC  A, D             ; Add High Byte 2 PLUS Carry from previous ADD
    LD   B, A             ; Store new High Byte in B (BC now holds the 16-bit result)

The Alternate Register Set

The Z80 has a mirrored set of all 8-bit and 16-bit registers (A’, F’, B’, C’, D’, E’, H’, L’). This “alternate set” provides a powerful way to save the entire state of the CPU instantly.

The Exchange Commands:

Instruction Action Purpose
EX AF, AF' Swaps the primary Accumulator (A/F) with the alternate (A’/F’). Used to swap the Accumulator and Flags (the most critical registers) quickly.
EXX Swaps the BC, DE, and HL pairs with their alternates (BC’, DE’, HL’). Used for a complete context switch of all main data pointers.

Fast Context Switching:

To save the entire working state of the Z80 (all 7 main 16-bit registers) in just two instructions:

    EX   AF, AF'      ; Swap Accumulator and Flags (A, F)
    EXX               ; Swap BC, DE, and HL pairs
    ; The program now runs using the alternate registers, leaving the
    ; previous program's state completely intact.