Skip to content
systemcoding.dev
Assembly

Learn Assembly the Retro Way: The Complete 6502 and Z80 Guide

Learn assembly language on the 6502 and Z80, from registers and flags to loops, 16-bit math, subroutines, interrupts and tooling, with worked programs for each.

24 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the Arm, AMD and Intel logos.

Modern assembly is hard to learn because the machine hides in plain sight. An x86-64 core has hundreds of instructions, a deep pipeline, out-of-order execution, virtual memory and a calling convention enforced by a compiler you did not write. An 8-bit CPU from the 1970s has none of that. The MOS Technology 6502 has 56 instructions, three working registers and a 64 KiB address space. The Zilog Z80 has a larger set and more registers, but it still fits in your head. You can hold the whole machine in mind, trace a program by hand and predict every register after every instruction. That is what makes them the best classroom for assembly, and it is the reason this guide starts there.

This is the hub of the assembly cluster on SystemCoding for retro CPUs. It teaches both chips from zero. By the end you will read and write programs for each, know which instruction does what to which flag, and understand the ideas that carry over to every processor you meet later: registers, flags, addressing modes, the stack, subroutines and interrupts. The guide is long on purpose. Each section builds a small working program, shows the register values the program leaves behind, and explains why the machine behaves that way.

A note on method before anything else. Every program here was written by reading the processor documentation, not by running an emulator, so the results shown are worked out by hand, instruction by instruction, and the guide shows you how to do the same. That is also a skill worth having: with an 8-bit CPU you can always trace the answer on paper.

What you need to know first

You need three ideas from outside assembly, and this section covers all of them.

Binary and hexadecimal. Both CPUs store everything as bytes, and a byte is eight bits, a number from 0 to 255. Assembly programmers write bytes in hexadecimal because one hex digit is exactly four bits. The byte 11111111 is $FF or 0xFF, which is 255. The 6502 tradition prefixes hex with $, and the Z80 tradition accepts $, 0x or a trailing h depending on the assembler. This guide uses $ for 6502 code and 0x for prose about Z80 values, and says which at each point.

Two's complement. Negative numbers fit in a byte by treating the top bit as a sign. $FF is also −1, $FE is −2, and $80 is −128. The same byte $FF is 255 when you read it as unsigned and −1 when you read it signed, and the CPU does not know or care which you meant. The flags tell you what happened, and you decide what the bits mean. That is the single most important mental shift from high-level languages, where the type carries the meaning.

Memory as an array of bytes. Both CPUs have a 16-bit address bus, so memory is 65,536 bytes numbered $0000 to $FFFF. Some of it is RAM, some is ROM, and some addresses are wired to chips such as a video controller or a sound generator. A store to the right address draws a pixel or plays a note. That is called memory-mapped I/O, and it is how the 6502 talks to hardware. The Z80 has memory-mapped I/O as well, and also a separate set of 256 or 65,536 port addresses reached with IN and OUT.

How an 8-bit CPU runs a program

A processor repeats one loop forever, called fetch, decode, execute. The program counter, PC, holds the address of the next instruction. The CPU reads the byte at that address, which is the opcode, and the opcode tells it how many operand bytes follow. It reads them, does the work, and advances PC past the whole instruction. Then it starts over.

Registers are the CPU's own storage, a few bytes that sit inside the chip and are much faster to use than memory. Because there are so few, assembly programming is mostly the art of deciding what lives in a register right now and what is parked in memory for later.

Flags are single bits that record facts about the last operation: the result was zero, the result was negative, an addition carried out of the top bit. Conditional branches read those flags. There is no if statement in assembly. There is "do something that sets flags, then branch if a flag is set".

An assembler turns the readable mnemonics (LDA #$05) into the bytes the CPU executes (A9 05). Labels become addresses, so you write BNE loop and the assembler works out the distance. A linker puts the pieces at the right places in memory. You will meet tools for both chips near the end of this guide.

The 6502 programmer's model

The 6502 has a deliberately tiny register file:

RegisterSizeRole
A8 bitsAccumulator: all arithmetic and logic happens here
X8 bitsIndex register and loop counter
Y8 bitsSecond index register and counter
SP8 bitsStack pointer, an offset into page one ($0100 to $01FF)
PC16 bitsProgram counter
P8 bitsProcessor status: the flags

There is no way to add two registers together directly, and no register-to-register MOV in the sense of the Z80. Everything funnels through A, with X and Y helping as counters and indexes. That feels cramped for about a day, and then it feels clear.

The status register P holds the flags, laid out as N V - B D I Z C from bit 7 down to bit 0:

BitFlagSet when
7N negativebit 7 of the result is 1
6V overflowa signed add or subtract overflowed
5unusedalways reads 1
4B breakset in the copy of P pushed by BRK and PHP
3D decimaladd and subtract work in BCD
2I interrupt disablemaskable interrupts are blocked
1Z zerothe result was zero
0C carryan add carried out, or a subtract did not borrow

The four you use every day are N, Z, C and V. A load such as LDA sets N and Z from the value loaded. Arithmetic sets all four. A store such as STA sets nothing, which matters: you can load a value, store it somewhere and branch on the loaded value afterward.

The 6502 memory map

The 6502 gives three regions special meaning. Page zero, $0000 to $00FF, is the zero page. Instructions that name a zero-page address are one byte shorter and one cycle faster than the same instruction with a full 16-bit address, so programs keep their hottest variables there. Page one, $0100 to $01FF, is the hardware stack. The stack pointer is only 8 bits and the CPU always adds $0100 to it, so the stack can never grow beyond 256 bytes. And the top six bytes of memory, $FFFA to $FFFF, hold three 16-bit vectors:

AddressVectorUsed when
$FFFA and $FFFBNMIa non-maskable interrupt arrives
$FFFC and $FFFDRESETthe CPU powers on or resets
$FFFE and $FFFFIRQ and BRKa maskable interrupt arrives, or BRK executes

Each vector is stored low byte first, because the 6502 is little-endian: the address $C000 appears in memory as 00 C0. On reset the CPU reads the word at $FFFC and jumps there, so a ROM must hold the start address of the program at the very top of memory. Every 6502 machine has that one fixed contract, and the machines differ only in what is wired to the rest.

Your first 6502 program

The program adds five numbers stored in a table and leaves the sum in a zero-page location. It uses the ca65 assembler syntax from the cc65 toolchain, which this guide uses throughout.

sum.sasm
        .org $0200

start:  LDX #$05            ; X counts 5 down to 1
        LDA #$00            ; A holds the running sum
loop:   CLC                 ; clear carry before every ADC
        ADC data-1,X        ; add table[X-1]
        DEX
        BNE loop            ; repeat until X reaches zero
        STA $10             ; store the sum in zero page
        BRK                 ; stop

data:   .byte 3, 1, 4, 1, 5

Read it as the CPU does. LDX #$05 loads the literal value 5 into X. The # means "the value itself", not "the memory at address 5". LDA #$00 zeroes the accumulator. In the loop, CLC clears the carry flag, ADC data-1,X adds the byte at address data - 1 + X plus the carry to A, DEX decrements X, and BNE loop branches back if the last result (the decrement) was not zero.

Two details trip up every beginner. First, ADC always adds the carry flag, so you clear it before an addition that should not include a carry from earlier. Forgetting CLC is the most common 6502 bug in the world. Second, DEX sets the zero flag when X hits 0, and BNE ("branch if not equal", really "branch if Z is clear") reads it. No compare instruction is needed because the decrement already set the flag.

Now trace it. X starts at 5 and the loop reads the table from the back, because data-1,X with X = 5 is the fifth byte:

PassX beforeByte readA after
1555
2416
33410
42111
51314

After pass 5, DEX makes X zero, BNE falls through, and STA $10 writes 14 to address $0010. The flags need care, because they are where hand tracing earns its keep. The last arithmetic instruction was the fifth ADC: it added 3 to 11 with the carry clear, giving 14 with no carry out. DEX then produced zero, so Z is set and N is clear. STA changes no flags, and BRK leaves A, X and the other flags alone. The final machine state is:

Text
A = $0E   X = $00   Y = $00   [$0010] = $0E
Flags: N=0 V=0 D=0 I=0 Z=1 C=0

When you are unsure what an instruction left behind, go back to the table of what it affects. Tracing is not slow once you have done it twenty times, and it is how you find the bug an emulator would only show you as a wrong number.

What the CPU actually executes

An assembler produces bytes, and you can produce the same bytes by hand with an opcode table. That is worth doing once, because it shows that nothing in the CPU knows about labels. Placing the program at $0200, the bytes and their addresses are:

AddressBytesInstruction
$0200A2 05LDX #$05
$0202A9 00LDA #$00
$020418CLC
$02057D 0D 02ADC $020D,X
$0208CADEX
$0209D0 F9BNE loop
$020B85 10STA $10
$020D00BRK
$020E03 01 04 01 05the table

Two of those encodings are worth decoding. ADC data-1,X becomes 7D 0D 02 because data is $020E, so data - 1 is $020D, written low byte first. And BNE loop is D0 F9: the operand is the signed distance from the byte after the branch ($020B) back to $0204, which is −7, and −7 in two's complement is $F9. A branch is a signed offset and the assembler computes it for you, which is why moving code around never breaks a branch until it moves too far, past the 127-byte reach.

Text
A2 05 A9 00 18 7D 0D 02 CA D0 F9 85 10 00 03 01 04 01 05

That string of 19 bytes is the whole program with its data. Load it at $0200 in any 6502 monitor, set PC to $0200, and it runs.

Logic, shifts and bit masks

Arithmetic is half of what a CPU does, and the other half is moving bits around. Both chips have AND, OR and XOR (the 6502 spells them AND, ORA and EOR), and both have shifts and rotates. Together they let you test, set and clear individual bits, which is how you talk to hardware registers whose bits each mean something.

A mask is a byte with ones where you care. To test whether bit 3 of a status byte is set, AND with %00001000 and check the zero flag. To set bit 3, OR with the mask. To clear it, AND with the inverted mask. To toggle it, XOR:

bits.sasm
        LDA $D012           ; some hardware register
        AND #%00001000      ; isolate bit 3
        BEQ bit_clear       ; Z=1 means bit 3 was 0

        LDA $10
        ORA #%00000100      ; set bit 2
        AND #%11111110      ; clear bit 0
        EOR #%10000000      ; toggle bit 7
        STA $10

If $10 holds $01, the three operations give $01 OR $04 = $05, then $05 AND $FE = $04, then $04 XOR $80 = $84. The 6502 also has BIT, which tests memory against A without changing A, copying bits 7 and 6 of the memory byte into N and V. It is a compact way to test a status register.

Shifts move bits one place. ASL shifts left and puts bit 7 into the carry, which doubles an unsigned number. LSR shifts right and puts bit 0 into carry, which halves it. ROL and ROR rotate through the carry flag, so they chain across bytes the way ADC does. A 16-bit left shift is ASL low followed by ROL high. The Z80 names are SLA, SRL, RL and RR, plus RLCA and its friends for the accumulator. Here is the Z80 way to test and set the same bits:

bits.asmasm
        in a,(0xFE)         ; read a port
        and 0x08            ; isolate bit 3
        jr z,bit_clear      ; zero flag set: bit 3 was 0

        ld a,(0x8000)
        or 0x04             ; set bit 2
        and 0xFE            ; clear bit 0
        xor 0x80            ; toggle bit 7
        ld (0x8000),a

The Z80 also has BIT, SET and RES instructions that test, set and clear a bit in any register or in (HL) directly, so set 2,a replaces the or mask. They are less useful in the 6502 world because the 6502 has no such instruction, and a good reason to learn masks first.

Common mistakes and how they look

Almost every beginner program fails in one of a handful of ways. Knowing the shapes saves hours:

SymptomCause on the 6502Cause on the Z80
Sum is off by oneADC without CLC firstadc used where add was meant
Value is wrong by 256carry lost between the bytes of a 16-bit addinc hl used where the carry mattered
Loop runs 256 timescounter loaded with zero, then decremented firstld b,0 then djnz, which runs 256 times
Program crashes at returnstack pointer never set, or PHA without PLApush without a matching pop
Reads garbage# forgotten, so the operand is an addressparentheses forgotten, so ld a,0x1234 is a value
Branch assembles but missestarget farther than 127 bytesjr target beyond its reach, use jp

The two entries about loop counts are worth a pause. Because a counter that starts at zero wraps to 255 on its first decrement, "run zero times" is not expressible with a plain decrement-and-branch loop. Check for zero before the loop starts if the count can be zero.

Addressing modes: where the operand lives

A mnemonic like LDA says what to do. The addressing mode says where the data comes from, and the 6502 has a rich set, which is one reason its code is compact. The ones you need first:

ModeSyntaxThe operand is
ImmediateLDA #$05the byte 5 itself
Zero pageLDA $10the byte at address $0010
AbsoluteLDA $1234the byte at address $1234
Zero page, XLDA $10,Xthe byte at $0010 + X, wrapping inside page zero
Absolute, XLDA $1234,Xthe byte at $1234 + X
Indirect, YLDA ($20),Yread the pointer at $20 and $21, add Y, load from there
Indexed indirectLDA ($20,X)add X to $20, read the pointer there, load from it
ImpliedINXno operand: the register is part of the opcode

The one to learn properly is LDA ($20),Y, because it is how a 6502 walks a buffer through a pointer. A 16-bit pointer lives in two adjacent zero-page bytes, and Y is the offset into whatever it points at. This copies a 4-byte string to a new buffer:

copy.sasm
src     = $20               ; zero-page pointer, 2 bytes
dst     = $22               ; zero-page pointer, 2 bytes

        .org $0200
start:  LDA #<message       ; low byte of the address
        STA src
        LDA #>message       ; high byte of the address
        STA src+1
        LDA #<$0300
        STA dst
        LDA #>$0300
        STA dst+1

        LDY #$00
copy:   LDA (src),Y         ; read through the source pointer
        STA (dst),Y         ; write through the destination pointer
        INY
        CPY #$04
        BNE copy
        BRK

message: .byte "HELO"

The < and > operators in ca65 take the low and high byte of an address, which is how you build a 16-bit pointer with two 8-bit stores. After BRK, address $0300 holds 48 45 4C 4F, the ASCII codes for HELO, and Y is 4. Because Y is a byte, one pass of this loop addresses at most 256 bytes. To copy more you increment the pointer's high byte too, which the 16-bit section covers.

Zero-page indexing wraps: LDA $FF,X with X = 2 reads address $0001, not $0101. That wrap is intentional and occasionally useful, and a source of strange bugs when you forget it.

Branches, comparisons and loops

All 6502 conditional branches are relative: the operand is a signed byte, so a branch reaches 128 bytes back or 127 bytes forward from the next instruction. There are eight, one for each state of four flags:

BranchTaken whenCommon meaning
BEQZ = 1equal, or zero
BNEZ = 0not equal
BCSC = 1carry set, unsigned greater or equal
BCCC = 0carry clear, unsigned less
BMIN = 1negative
BPLN = 0positive or zero
BVSV = 1signed overflow
BVCV = 0no signed overflow

CMP, CPX and CPY subtract without storing the result and set N, Z and C from it. After CMP #$0A, the carry is set when A is 10 or more (an unsigned comparison) and Z is set when A is exactly 10. So "is A less than 10?" is CMP #$0A followed by BCC and "is A equal to 10?" is CMP #$0A followed by BEQ.

Here is a loop that finds the largest byte in a table, a program with a branch inside a loop:

max.sasm
        .org $0200
start:  LDX #$04            ; index of the last element
        LDA table,X         ; assume the last element is the maximum
scan:   DEX
        BMI done            ; X went below zero: every element seen
        CMP table,X         ; compare A with table[X]
        BCS scan            ; A >= table[X]: keep A
        LDA table,X         ; otherwise table[X] is the new maximum
        JMP scan
done:   STA $10
        BRK

table:  .byte 12, 200, 7, 90, 31

Trace it. A starts as 31 (the element at index 4). DEX makes X 3, CMP table,3 compares 31 with 90, carry is clear (31 is less than 90), so BCS is not taken and A becomes 90. X = 2: compare 90 with 7, carry set, keep 90. X = 1: compare 90 with 200, carry clear, A becomes 200. X = 0: compare 200 with 12, carry set. Then DEX gives $FF, which has bit 7 set, so BMI is taken and the loop ends. The result:

Text
A = $C8   X = $FF   [$0010] = $C8

$C8 is 200. The loop test BMI after DEX is a standard 6502 idiom: a counter that counts down through zero turns negative, which works while the table has no more than 128 entries.

The comparison above is unsigned. If those bytes were signed values, 200 would be −56 and the answer would be 90. Signed comparison needs the V flag and a combination of N and V, which the intermediate posts in this cluster cover. The beginner rule is simple: know in advance whether the data is signed.

The stack and subroutines

The stack is memory used last-in, first-out, and the 6502 stack pointer starts wherever the program puts it, usually $FF, meaning the first push lands at $01FF and the stack grows downward. You push with PHA (push A) and PHP (push P), and pull with PLA and PLP. TXS and TSX move values between X and SP, and they are how you set the stack pointer at reset.

JSR (jump to subroutine) pushes the return address and jumps. RTS pulls the address and resumes after the call. One quirk of the 6502 is that JSR pushes the address of the last byte of its own instruction, not the next instruction, and RTS adds one to the pulled value. You almost never notice, but a program that fiddles with the stack to return early must remember it.

A subroutine that multiplies the accumulator by 10 shows the whole mechanism, since 10 × A is (A × 8) + (A × 2), and a left shift multiplies by two:

times10.sasm
        .org $0200
start:  LDA #$07
        JSR times10         ; A = 70
        STA $10
        BRK

times10:
        ASL                 ; A = A * 2
        STA $11             ; keep A*2 in zero page
        ASL                 ; A * 4
        ASL                 ; A * 8
        CLC
        ADC $11             ; A*8 + A*2
        RTS

ASL shifts the accumulator left one bit. With A = 7, the shifts give 14, 28 and 56, and 56 plus the saved 14 is 70. This subroutine works only while the result fits in a byte, 25 or less on input, and nothing checks that. In assembly, ranges are your responsibility.

Calling convention is whatever you decide. Here the argument and the result both travel in A. Larger routines pass parameters in zero-page locations or on the stack, and the documentation comment above each subroutine says which registers it destroys. With only three registers, preserving them is a real cost, so many 6502 programs just document what is clobbered.

16-bit arithmetic with the carry flag

A byte only goes to 255, so real programs build bigger numbers from several bytes, and the carry flag is what links them. Adding two 16-bit numbers is two 8-bit additions, low bytes first, and the carry from the first feeds the second. This adds $12FF and $0001:

add16.sasm
        .org $0200
start:  CLC
        LDA #$FF            ; low byte of the first number
        ADC #$01            ; plus the low byte of the second
        STA $10             ; low result
        LDA #$12            ; high byte of the first number
        ADC #$00            ; plus the high byte of the second, plus carry
        STA $11             ; high result
        BRK

The low addition is $FF + $01 = $100, which is $00 with a carry out. The high addition is $12 + $00 + 1 = $13. The result at $0010 is the 16-bit value $1300, stored low byte first:

Text
[$0010] = $00   [$0011] = $13

Without the carry the answer would be $1200, wrong by 256. Subtraction mirrors it: SEC before the first SBC, because on the 6502 the carry flag works as the inverse of a borrow. The detail that catches people is that SBC computes A − operand − (1 − C), so a clear carry subtracts an extra one.

The Z80 programmer's model

The Zilog Z80 launched in 1976 as a superset of the Intel 8080, and it has the larger register file:

RegisterSizeRole
A8 bitsAccumulator, as on the 6502
F8 bitsFlags
B, C, D, E, H, L8 bits eachGeneral purpose, usable alone or as pairs BC, DE, HL
IX, IY16 bitsIndex registers with a signed 8-bit displacement
SP16 bitsStack pointer, anywhere in memory
PC16 bitsProgram counter
I, R8 bitsInterrupt vector base and memory refresh counter
A', F', BC', DE', HL'Shadow set, swapped in by EXX and EX AF,AF'

The pairs matter as much as the single registers. HL is the Z80's pointer: LD A,(HL) reads the byte HL addresses, and INC HL advances it. BC is a counter for block instructions and DE is a destination. 16-bit arithmetic works directly: ADD HL,DE adds two 16-bit values in one instruction, something the 6502 cannot do at all.

The flags register holds, from bit 7 down, S Z - H - P/V N C:

FlagMeaning
S signbit 7 of the result
Z zeroresult was zero
H half carrycarry out of bit 3, used by decimal adjust
P/V parity or overflowparity after logic instructions, signed overflow after arithmetic
N subtractthe last operation was a subtraction
C carrycarry out, or borrow on subtract

Two bits of the register, 5 and 3, have no documented purpose and copy bits of the result. Programs should not depend on them.

On a Z80 the stack pointer is a full 16-bit register. PUSH and POP work on register pairs (PUSH HL), and the programmer decides where the stack lives. There is no hardware stack page, no fixed reset vector table, and the CPU starts executing at address 0x0000 after reset.

Your first Z80 program

The same task, summing five bytes, shows how differently the Z80 solves it. This uses the sjasmplus assembler, whose syntax follows the Zilog mnemonics:

sum.asmasm
        org 0x8000

start:  xor a               ; A = 0 and carry cleared in one instruction
        ld b,5              ; B is the loop counter
        ld hl,data          ; HL points at the table
loop:   add a,(hl)          ; add the byte HL points at
        inc hl              ; move to the next byte
        djnz loop           ; B = B - 1, jump if B is not zero
        ld (result),a       ; store the sum
        halt

data:   db 3,1,4,1,5
result: db 0

Compare it with the 6502 version. There is no CLC because XOR A zeroes A and clears carry as a side effect, and the loop does not need it again because ADD A,(HL) does not include the carry (ADC does). The loop counter does not use a DEC and a branch: DJNZ decrements B and jumps if the result is nonzero, in one instruction, and it does not touch the flags. Registers B and HL do separate jobs, and the pointer advance with INC HL leaves the flags alone as well, since 16-bit increments never change flags on the Z80.

The trace is the same arithmetic as before: A goes 3, 4, 8, 9, 14 across five passes and finishes as 0x0E. The final state:

Text
A = 0x0E   B = 0x00   HL = address of result
Flags: Z=0 C=0 (the last ADD gave 14, with no carry and a nonzero result)

Notice that Z is clear here, where the 6502 version left it set. That difference is not a bug. The 6502 loop ended on a decrement that produced zero, so Z was set. The Z80 loop ends on DJNZ, which never modifies flags, so the flags still describe the last ADD. Flag state at the end of a loop depends on which instruction last wrote it, and a program should never rely on flags surviving across instructions that might change them.

Z80 strengths: block instructions and 16-bit moves

The Z80's block instructions move or search memory with one instruction. LDIR copies BC bytes from (HL) to (DE), incrementing both pointers and decrementing BC until it reaches zero. Copying the 4-byte message from the 6502 example becomes:

copy.asmasm
        org 0x8000
start:  ld hl,message       ; source
        ld de,0x9000        ; destination
        ld bc,4             ; byte count
        ldir                ; copy until BC = 0
        halt

message: db "HELO"

After LDIR, BC is zero, HL points one byte past the end of the source and DE one byte past the end of the destination:

Text
[0x9000..0x9003] = 48 45 4C 4F   BC = 0x0000
HL = message + 4   DE = 0x9004

The 6502 needs a loop with an index and a compare for the same job, which is why Z80 machines such as the ZX Spectrum can clear and copy screen memory so quickly. CPIR is the search cousin: it compares A with (HL) repeatedly until a match or until BC runs out. Both are explored in the intermediate posts.

The shadow registers let you save an entire register set in two instructions: EXX swaps BC, DE and HL with their primes and EX AF,AF' swaps the accumulator and flags. An interrupt routine uses them to avoid pushing anything, which makes interrupt latency tiny. The cost is that the main program cannot use the shadow set at the same time.

16-bit arithmetic on the Z80

The Z80 treats register pairs as 16-bit numbers, so the $12FF + $0001 sum that needed two additions and a carry on the 6502 is one instruction:

add16.asmasm
        ld hl,0x12FF
        ld de,0x0001
        add hl,de           ; HL = 0x1300
        ld (0x9000),hl      ; store HL, low byte first
        halt
Text
HL = 0x1300   [0x9000] = 00   [0x9001] = 13
Flags: C=0 N=0 (H=1: a carry crossed bit 11)

The stored bytes appear in the same order the 6502 version produced, 00 13, because both chips are little-endian. Two cautions belong with ADD HL,DE. It updates only the C, H and N flags and leaves Z and S as they were, so you cannot test the 16-bit result for zero straight after it. And there is no 16-bit compare, so equality of two pairs takes or a to clear the carry, then sbc hl,de, which sets Z properly, at the cost of destroying HL. These are the places where the Z80's convenience runs out, and they are the first things a Z80 programmer memorizes.

6502 and Z80, side by side

The same ideas show up in both chips with different names, and learning them in pairs makes both easier:

Task6502Z80
Load a constantLDA #$05ld a,5
Load from memoryLDA $1234ld a,(0x1234)
Store to memorySTA $1234ld (0x1234),a
Increment a registerINXinc b
Add with carryADC #$01adc a,1
CompareCMP #$0Acp 10
Branch if zeroBEQ labeljr z,label
Loop counterDEX, BNEdjnz
Call and returnJSR, RTScall, ret
Clear the carryCLCor a
Set the carrySECscf
Interrupt returnRTIreti or retn

Three structural differences explain most of the others. The 6502 has one accumulator and uses memory addressing tricks, such as the zero page and indirect indexing, to make up for the lack of registers. The Z80 has many registers and 16-bit operations, so it keeps values in registers and uses fewer addressing modes. And the 6502 uses clock cycles cleverly: many instructions take 2 to 4 cycles, while the Z80 typically needs 4 to 23. At the same clock rate a 6502 does more work, and in practice the 6502 in a Commodore 64 ran near 1 MHz while the Z80 in a ZX Spectrum ran at 3.5 MHz, so the two machines ended up in the same performance neighborhood.

Interrupts

An interrupt makes the CPU stop what it is doing, run a handler, and resume. Both chips have the maskable kind, from timers and video hardware, and the non-maskable kind, which cannot be disabled and is used for events such as a reset button or a vertical blank.

On the 6502, IRQ is maskable through the I flag, set with SEI and cleared with CLI. When an interrupt arrives the CPU pushes PC and P, sets I, and jumps through the vector at $FFFE. A handler ends with RTI, which pulls P and PC back. The CPU does not save A, X or Y, so a handler that uses them pushes them first:

irq.sasm
irq:    PHA                 ; save A
        TXA
        PHA                 ; save X (via A)
        INC $10             ; count the interrupt in zero page
        PLA
        TAX                 ; restore X
        PLA                 ; restore A
        RTI

The INC $10 here does not touch any register, so the saves are not needed for this body; they are shown because the pattern matters once the handler grows. Notice the cost of TXA and PHA: the 6502 has no instruction to push X directly, which is one of the places the tiny register file shows.

On the Z80 a maskable interrupt is enabled with EI and disabled with DI, and three modes decide where it goes. In mode 1, set by IM 1, the CPU jumps to 0x0038, as if it executed RST 38h. That is the mode the ZX Spectrum uses for its 50 Hz frame interrupt. The non-maskable interrupt always jumps to 0x0066. The Z80 pushes only PC, so a handler saves what it uses, or uses the shadow set:

irq.asmasm
        org 0x0038
irq:    ex af,af'           ; swap in the shadow accumulator and flags
        exx                 ; swap in the shadow BC, DE and HL
        ld hl,frames
        inc (hl)            ; count one frame
        exx
        ex af,af'
        ei                  ; interrupts are off on entry, so turn them on
        reti

frames: db 0

Two details are worth noting. The shadow swap makes the handler transparent: the main program's registers come back untouched. And EI appears before RETI because the CPU disables interrupts on acceptance, and the handler must re-enable them. The instruction after EI still executes before a new interrupt is taken, so EI followed by RETI cannot be re-entered by the same event.

Tools you will use

You do not need real hardware to learn either chip. A short list gets you everywhere:

Need6502Z80
Assembler and linkerca65 and ld65 from cc65, or acme, 64tasssjasmplus, z80asm, or z88dk
Quick experiments in a browserthe Easy 6502 tutorial simulatora browser Z80 emulator
Machine emulatorsVICE for the Commodore 64, Mesen for the NESFuse for the ZX Spectrum, MAME
Monitor and debuggerVICE built-in monitorFuse debugger
Referencethe 6502.org documentation and the MOS and WDC datasheetsthe Zilog Z80 CPU User Manual

Use a datasheet as the final authority. This guide names the official documents for each chip because secondary tables on web pages carry mistakes, especially cycle counts and undocumented behavior. The Zilog manual lists the flag effects of every instruction, and the MOS programming manual does the same for the 6502.

A route through the rest of the cluster

Learn in this order, and stop when you have what you need:

  1. Registers, flags and your first program for one chip, then the other.

  2. Addressing modes, because they determine how you structure data.

  3. Loops, comparisons and the stack, which give you subroutines.

  4. Multi-byte arithmetic, which every real program needs.

  5. A real machine: the Commodore 64, NES, ZX Spectrum or Game Boy, where you draw something on screen.

  6. Cycle counting and interrupts, the skills that separate a demo from a game.

Skip decimal mode, undocumented opcodes and bank switching on a first pass. They are interesting and they matter for particular machines, but nothing in the earlier steps depends on them.

Where this approach does not fit

Retro assembly is a classroom, not a career path in itself. Modern processors differ in ways the 8-bit chips never show: caches, pipelines, memory ordering, privilege levels, vector units. The skill carries over (reading a flag, tracing a register, understanding an addressing mode), and the details do not. If your goal is to write fast code for a laptop, finish this guide, then move to the x86-64 or Arm material in this cluster rather than staying here.

There is also a trade-off in how much you gain from a hand-traced program. A real emulator shows you the machine state after every instruction and catches your mistakes in seconds. Tracing by hand teaches you the semantics, and an emulator checks them. Use both, in that order.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.