Re: divide by 10 with Z80



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

.



Relevant Pages

  • Re: divide by 10 with Z80
    ... ;quotient in H, remainder in L ... Note from Herb. ...
    (comp.os.cpm)
  • Re: divide by 10 with Z80
    ... ;quotient in H, remainder in L ... Note from Herb. ...
    (comp.os.cpm)
  • [SUMMARY] Long Division (#180)
    ... is done repeatedly dividing the divisor into each digit of the ... dividend combined with the remainder of the previous division step. ... And so our quotient is 0372, usually written without leading zeros as ...
    (comp.lang.ruby)
  • Re: divide by 10 with Z80
    ... The quotient is the track while the remainder is the sector. ... one could do maybe 2 or 3 compares of the remainder to determine ... It will work if I shift the answer in HL right by 1. ...
    (comp.os.cpm)
  • Re: Im officially embarrased
    ... the dividend and which is the devisor: Is the first number, ... just not which is the divisor and which is the dividend in this ... leaving a whole number as remainder. ... For instant the quotient on dividing 30 by 7 is 4, ...
    (sci.math)