## Re: [stella] Divide by 3

 Subject: Re: [stella] Divide by 3 From: David Galloway Date: Sat, 18 Dec 2004 19:05:38 -0800
Paul Slocum wrote:

Is there an easy way to do it without a loop or table?

-paul

A question would be how accurate do you need the result to be?

Without a loop or table will have to be some type of unwound hardcoded multiplication by the reciprocal.

1/3 in 8.8 form is 00.55 (in hex)

0.55 is 00000000.01010101

```To multiply N * 85 unwound you need to add together
(N << 6 ) + (N << 4) + (N<<2) + (N)```

```Example:
477 / 3```

```477 * 64 =   30528
477 * 16 =     7632
477 *  4 =       1908
477  *  1 =         477
-----------------------
40545 / 256  = 158.3```

477 / 3 = 159

If you need more accuracy you could also add on 477 * 256 and then divide the full result by 512 instead of 256.
But obviously the /256 is easier because you just select the appropriate byte.

;A quick and dirty unsigned divide by three off the top of my head.(untested)
;This is essentially an 8 bit routine but it can handle input up to 255 * 3
; I'll maybe try to optimize it and increase the precision after the christmas party...

lda num2divLow
sta shiftr
lda num2divHigh (or could be lda #0 if this will only be 0-255 input)
sta result ; * 1
asl shiftr
rol
asl shiftr
rol ; * 4
adc result ; this would be better if you added one more if bit 7 in shifter were set
sta result
asl shiftr
rol
asl shiftr
rol ; * 16
adc result ; this would be better if you added one more if bit 7 in shifter were set
sta result
asl shiftr
rol
asl shiftr
rol ; * 64
adc result ; this would be better if you added one more if bit 7 in shifter were set
sta result
rts