6502 Beginner Tips

From 8BitDev.org - Atari 7800 Development Wiki
Revision as of 05:42, 19 December 2015 by MSaarna (talk | contribs) (Created page with "==6502 Beginner Tips== This entry assumes you're new but familiar with 6502 assembly. If that isn't true, you may wish to check out ===6502 if...then equivalents=== If yo...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

6502 Beginner Tips

This entry assumes you're new but familiar with 6502 assembly. If that isn't true, you may wish to check out


6502 if...then equivalents

If you're learning 6502 assembly with a background in a higher language, the following table presents typical logic comparisons in a more familiar format.

6502 if...then equivalents
test desired comparison branch
A = VALUE CMP #VALUE BEQ
A <> VALUE CMP #VALUE BNE
A > VALUE CMP #VALUE BEQ and then BCS
A >= VALUE CMP #VALUE BCS
A < VALUE CMP #VALUE BCC
A <= VALUE CMP #VALUE BEQ and then BCC
A = $ADDR CMP $ADDR BEQ
A <> $ADDR CMP $ADDR BNE
A > $ADDR CMP $ADDR BEQ and then BCS
A >= $ADDR CMP $ADDR BCS
A < $ADDR CMP $ADDR BCC
A <= $ADDR CMP $ADDR BEQ and then BCC

Similar tests can be made for X or Y instead of A, substituting CPX or CPY for CMP.


divide/multiply by powers of 2

On the 6502, the easiest way to multiply a value by 2 is to shift the bits of the value one place to the left. e.g. "ASL" or "ASL VALUE"

Similarly, you can divide by 2 by shifting the bits of the value one place to the right. e.g. "LSR" or "LSR VALUE"

Repeated shifts allow for operations with other powers of 2. e.g. 2 shifts for a divide/multiply by 4, 3 shifts for a divide/multiply by 8, etc.

Often you can design games to take advantage of powers of 2 divide/multiply, rather than using other values that are less easily manipulated by the 6502.


multiply by near powers of 2

In a pinch, you can multiply by 3 by performing a left shift (multiply by 2) followed by an addition of the original value. Perform another left shift for a multiply by 6.

Similarly you can multiply by 5 by performing two left shifts (multiply by 4) and an addition of the original value.

The alternative approach to above, is creating a look-up table for multiplication by the desired value. While this is much faster, it can use a lot of ROM. You'll need to figure out whether the trade-off is worthwhile in your application.

lookup tables instead of complex math

2's complement

negating numbers dividing by 2 while preserving sign

avoid double jsr

You should avoid double JSRs followed by RTSs, like the following...

MySubRoutine
 LDA PlayerX
 JSR MultiplyBy2
 RTS
MultiplyBy2
 ASL
 RTS

Instead you can save stack and cycle overhead by changing the first JSR into a JMP...

MySubRoutine
 LDA PlayerX
 JMP MultiplyBy2
MultiplyBy2
 ASL
 RTS


16-bit data

store in 2 tables

16-bit increment without 16-bit addition