I love finding this forum. It's been 45 years since I was deep into the 6502. Now I'm out of touch with standard nomenclature and current tools. Your spit and polish is appreciated.
I have a special case need for an algorithm that quickly divides by three. The largest dividend we'll face is 765. It's 10 bits, and when divided by 3, gives us the largest quotient we'll face of 255, which is 8 bits.
To divide by 3, we can multiply by 1/3.
In binary, 1/3 is 0.01010101..., repeating forever. In spite of not having an exact quantity for 1/3, we can use the 8 bits after the decimal to accurately calculate an 8 bit quotient from our ten bit dividend. Since the 6502 lacks a multiply operation, we can use the add operation as indicated by the four bits of 0.01010101 that are set high.
I'm using the 6502's zero page to serve as registers. To accumulate a sum, we'll repeatedly shift the bits and add. Can you suggest a better way? How does my nomenclature need spiffed up? Any comment is welcome.
Code:
;-----------------------------------------------------------------
; The dividend is stored in 00 and 01 before calling this routine.
; The resulting quotient will be accumulated in 03.
; Largest supported dividend is 765. (add error checking?)
DIVLO = $00 ; Zero page locations of 10 bit dividend
DIVHI = $01
QUOLO = $02 ; low bits of accumulated sum
QUOHI = $03 ; high bits of accumulated sum (Quotient)
DIVIDE_BY_THREE:
; First, effectively multiply by 0.0000 0001
lda DIVLO ; low bits of dividend
sta QUOLO
lda DIVHI ; high bits of dividend
; shift 6 times, add 3 times
ldx #3 ; so, we'll loop 3 times
; Then, effectively multiply by 0.0000 0101
; then by 0.0001 0101
; then by 0.0101 0101, which is 1/3
LOOP:
sta QUOHI
asl QUOLO ; first, shift left twice
rol QUOHI
asl QUOLO
rol QUOHI
clc ; Then, add the dividend
lda QUOLO
adc DIVLO
sta QUOLO
lda QUOHI
adc DIVHI
dex
bne LOOP
FINISH:
sec
adc #0 ; + 1 (round up)
sta QUOHI ; The resulting Quotient is in the Accumulator
rts
Thank you.