View Single Post
Old 26th May 2019, 9:11 pm   #1
julie_m
Dekatron
 
Join Date: May 2008
Location: Derby, UK.
Posts: 7,735
Default Fun with 6502 Assembler

I've been doing some 6502 assembly language programming, and I thought I would share a few techniques I found in case they come in useful to anyone else. No originality is claimed on any of the following .....

To perform any arbitrary series of instructions exactly twice and then RTS, you can use something like:
Code:
LDX #0
CLC
JSR sub
.sub
LDA m1,X
ADC m2,X
STA m3,X
INX
RTS
Line 1 sets the X register to 0.
Line 2 clears the carry flag.
Line 3 pushes the return address onto the stack, and jumps to (the very next instruction) line 4.
Line 4 is just a label for the beginning of a subroutine.
Lines 5 et seq are where the magic happens.
Line 8 increases X, so we will be using the next bytes up in memory the next time we go round the loop.
Line 9 is the end of the subroutine. The RTS takes us back to the address we stored at line 3, and the program continues from line 4.
Lines 5 onwards do the magic all over again.
When we get to line 9 the second time around, the RTS returns to wherever we came from.

It adds just three bytes to the program size (for the extra RTS instruction) and twelve cycles (six for the first JSR and another six for the RTS that takes us to the top the second time) to the execution time.


If you are doing bit-packing, you probably need to do several LSR or ASL instructions in a row. The fastest way is to do the bit-shifting right in the accumulator (LSR A and ASL A only take two cycles; as opposed to 5 cycles for zero page, 6 for zero page, X and absolute or 7 cycles for absolute,X -- no other addressing modes are available). If you have something like
Code:
.lsr4
LSR A
.lsr3
LSR A
.lsr2
LSR A
LSR A
RTS
then you can JSR into any of the instructions to shift the accumulator contents to the right 4, 3 or 2 bytes.
__________________
If I have seen further than others, it is because I was standing on a pile of failed experiments.
julie_m is offline