Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;===============================================================
- ;*As a note, "8 cycle routine" means that the algorithm runs
- ;8 times. After that, cycle refers to clock cycles.
- ;
- ;This routine was written for the Z80 processor on 30 May 2011.
- ;This is a simple, fast, 8 cycle routine to find the square root
- ;of hl. If you would like an explanation of the algorithm, or
- ;if you have any other questions, you can contact me at:
- ; xedaelnara@gmail.com
- ;
- ;This is a simple derivation of how I learned it by hand and is
- ;much easier in binary :)
- ;
- ;There are plenty of ways to vary this such as returning a
- ;rounded result, returning the z flag set if it is a perfect
- ;square, returning the result in bc, returning cubed roots, et
- ;cetera.
- ;
- ;To use this, copy this to the program that needs it and then
- ;use "call SqrtHL" as needed :)
- ;===============================================================
- SqrtHL:
- ;===============================================================
- ;Inputs:
- ; hl is the value to find the square root of
- ;Outputs:
- ; a is the square root (the integer part)
- ; bc is not changed
- ; de is not changed
- ; hl is 0
- ; interrupts are turned off
- ;Shadow Registers:
- ; a' is not changed
- ; b' is 0
- ; c' is not changed
- ; h'l' is the remainder (the original value minus a^2)
- ;Destroys:
- ; d'e'
- ;===============================================
- ;mnemonic size cycles total
- ;===============================================
- di ;1 4 4
- exx ;1 4 4
- xor a ;1 4 4
- ld h,a ;1 4 4
- ld l,a ;1 4 4
- ld b,8 ;2 7 7
- sqrtHLLoop:
- rlca ;1 4 32
- ld d,0 ;2 7 56
- ld e,a ;1 4 32
- ex de,hl ;1 4 32
- add hl,hl ;1 11 88
- inc l ;1 4 32
- ex de,hl ;1 4 32
- exx ;1 4 32
- add hl,hl ;1 11 88
- exx ;1 4 32
- adc hl,hl ;2 15 120
- exx ;1 4 32
- add hl,hl ;1 11 88
- exx ;1 4 32
- adc hl,hl ;2 15 120
- sbc hl,de ;2 15 120
- jr c,$+5 ;5 12|23 96+11x
- inc a ;-- -- --
- jr $+3 ;-- -- --
- add hl,de ;1 11 88
- djnz sqrtHLLoop ;2 13|8 99
- exx ;1 4 4
- ret ;1 10 10
- ;
- ;Size : 37 bytes
- ;Speed : 1292+11x cycles
- ; x is the number of bits in the result, so speed ranges from
- ; 1292 cycles to 1380. To put this into perspective, at the
- ; slowest setting (6MHz), the calculator can run this over
- ; 4500 times in a second
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement