<< Previous Message Main Index Next Message >>
<< Previous Message in Thread This Month Next Message in Thread >>
Date   : Fri, 03 Jun 2005 23:54:33 +0100
From   : jgh@... (Jonathan Graham Harston)
Subject: Re: Assembly Language Square Root

Ooo goody! 6502<->z80 conversion!
 
I couldn't get an exact opcode-for-opcode translation working[1], but
here's one I did earlier ;)
 
eg, in=&70:out=&72
 
.sqr                            :\ On entry, !in=input value
LDY #1:STY out+0:DEY:STY out+1  :\ Initialise out to first subtrand
.sqr_loop                      :\ Repeatedly subtract increasing
SEC                             :\   odd numbers until in<0
LDA in+0:TAX:SBC out+0:STA in+0 :\ in=in-subtrand, remainder in X
LDA in+1:SBC out+1:STA in+1
BCC sqr_done                    :\ in<0, all done
INY                             :\ 
LDA out+0:ADC #1:STA out+0      :\ step +2 to next odd number
BCC sqr_loop                   :\ no overflow, subtract again
INC out+1:BNE sqr_loop         :\ INC high byte and subtract again
.sqr_done
STY out+0:STX out+1             :\ out?0=root, out?1=remainder
RTS
:
This works by counting how many times increasing odd numbers
can be subtracted until there's nothing left.
 
For example:
 
32-1=31 -> 31-3=28 -> 28-5=23 -> 23-7=16 -> 16-9=7 -> 7-11<0
        1          2          3          4          5
 
-> SRQ(30)=5, remainder 7
 
You can test it with:
 
FOR A%=1 to 65535:!in=A%:CALL sqr:P.A%,out?0,out?1:NEXT
 
If you're interested in other machine code aritmetic, there's
some constant-execution speed multipliation and division code
at mdfs.net/User/JGH/Progs/ConstMul and ConstDiv
________________
[1]
Direct translation, couldn't get working :(
 
.sqr16
LDA #0:STA d:LDA #&40:STA e\>  ld de,#0040
LDA l:PHA\>  ld a,l
LDA h:STA l\>  ld l,h
LDA d:STA h\>  ld h,d
SEC\>  or a
LDX #8\>  ld b,8
.sqr16_loop\> Sqr16_Loop:
LDA l:SBC e:STA l\>  sbc hl,de
LDA h:SBC d:STA h
PHP:PLA:EOR #1:PHA:PLP
BCS sqr16_skip\>  jr nc,Sqr16_Skip
CLC
LDA l:ADC e:STA l\>  add hl,de
LDA h:ADC d:STA h
.sqr16_skip\> Sqr16_Skip:
PHP:PLA:EOR #1:PHA:PLP\>  ccf
ROL d\>  rl d
PLA:ASL A:PHA\>  add a,a
LDA l:ADC l:STA l\>  adc hl,hl
LDA h:ADC h:STA h
PLA:CLC:ASL A:PHA\>  add a,a
LDA l:ADC l:STA l\>  adc hl,hl
LDA h:ADC h:STA h
PHP:PLA:EOR #1:PHA:PLP
DEX:BNE sqr16_loop\>  djnz Sqr16_Loop
PLA:RTS\>  ret
 
-- 
J.G.Harston - jgh@...                - mdfs.net/User/JGH
Sheffield Boundary Review at http://mdfs.net/User/JGH/Docs/Politics/ParlReview
<< Previous Message Main Index Next Message >>
<< Previous Message in Thread This Month Next Message in Thread >>