Re: divide by 10 with Z80
- From: "dkelvey@xxxxxxxxxxx" <dkelvey@xxxxxxxxxxx>
- Date: Wed, 23 Jan 2008 11:43:33 -0800 (PST)
On Jan 22, 5:14 pm, Herb Johnson <herbrjohn...@xxxxxxxxx> wrote:
On Jan 22, 2:29 pm, "dkel...@xxxxxxxxxxx" <dkel...@xxxxxxxxxxx> wrote:
; divide number between 0 and 800 by 10
; hl = dividend
; returns:
; a = quotient
; h = remainder
Joseph carr "z-80 microcomputer handbook" p. 190. Put
the 16-bit value in HL, put the 8 bit value in C and zero in B.
Then shift HL left and subtract BC successively. In effect you
are shifting BC right relative to HL.and doing "long division"
Feed the results into the lower bits of HL as you shift HL to the
left.
divide8:
;B has 8 bit divider, HL the "16-bit" dividend
;quotient in H, remainder in L
;successive shift and subtract operations
LD C,0
LD D,8 ;shift counter
LOOP ADD HL,HL ;shift HL left
XOR A,A ;clear carry
SBC HL,BC ;subtact divisor from UPPER byte
INC HL ;presume result "good"
JP P,JUMP1 ;jump if positive result
ADD HL,BC ;if negative, restore first
JUMP1: RES 0,L ;and clear bit 0 in L
DEC D ;count down 8 shifts
JR NZ,LOOP ;and loop until none
Note from Herb. I don't think this works if HL has a value
above 32K decimal. Looks to me like the first "ADD HL,HL" effectively
left-shifts bit 15 to oblivion. But for the required value of 0 to
800,
that's not a problem. Like any code in a book, check it throughly
for problems and marginal conditions; make sure you avoid "feeding"
it values it won't handle. (What happens if B=0?)
Herb Johnson
"don't try to be a programmer, Herb" - French Luser
retrotechnology.com
Hi Herb
Results are backwards. L is the quotient and H is the remainder.
At least it won't hang if B=0 but it could check for that.
It would be more optimal if the ADD HL,BC and SBC HL,BC were
swapped and use the carry flag like I use. SBC uses 15 clock
cycles compared to 11. It is better to have the conditional do the
extra clocks than to do it for each loop. Worst case is the same
but best case is better.
Dwight
.
- References:
- divide by 10 with Z80
- From: dkelvey@xxxxxxxxxxx
- Re: divide by 10 with Z80
- From: Herb Johnson
- divide by 10 with Z80
- Prev by Date: Re: divide by 10 with Z80
- Next by Date: Re: Towards a GREP Utility for WS4 Files... The end?
- Previous by thread: Re: divide by 10 with Z80
- Next by thread: Re: divide by 10 with Z80
- Index(es):
Relevant Pages
|