1 ;; Originally from GBDK by Pascal Felber.
113 ; Fall through to __div16
124 ;; If divisor is non-zero, carry=0
125 ;; If divisor is 0, carry=1 and both quotient and remainder are 0
127 ;; Register used: AF,BC,DE,HL
130 ;; Determine sign of quotient by xor-ing high bytes of dividend
131 ;; and divisor. Quotient is positive if signs are the same, negative
132 ;; if signs are different
133 ;; Remainder has same sign as dividend
134 ld a,b ; Get high byte of dividend
135 push af ; Save as sign of remainder
136 xor d ; Xor with high byte of divisor
137 push af ; Save sign of quotient
139 ;; Take absolute value of divisor
141 jr Z,.chkde ; Jump if divisor is positive
142 sub a ; Substract divisor from 0
145 sbc a ; Propagate borrow (A=0xFF if borrow)
148 ;; Take absolute value of dividend
151 jr Z,.dodiv ; Jump if dividend is positive
152 sub a ; Substract dividend from 0
155 sbc a ; Propagate borrow (A=0xFF if borrow)
158 ;; Divide absolute values
161 jr C,.exit ; Exit if divide by zero
162 ;; Negate quotient if it is negative
163 pop af ; recover sign of quotient
165 jr Z,.dorem ; Jump if quotient is positive
166 sub a ; Substract quotient from 0
169 sbc a ; Propagate borrow (A=0xFF if borrow)
173 ;; Negate remainder if it is negative
174 pop af ; recover sign of remainder
176 ret Z ; Return if remainder is positive
177 sub a ; Substract remainder from 0
180 sbc a ; Propagate remainder (A=0xFF if borrow)
193 ; Fall through to divu16
197 ;; Check for division by zero
200 jr NZ,.divide ; Branch if divisor is non-zero
201 ld b,d ; Divide by zero error: D=E=0
203 scf ; Set carry, invalid result
208 ld b,#16 ; 16 bits in dividend
210 ;; Cleaned up on April 2009 by Marco Bodrato(http://bodrato.it/ )
211 ;; Shift next bit of quotient into bit 0 of dividend
212 ;; Shift next MSB of dividend into LSB of remainder
213 ;; AC holds both dividend and quotient. While we shift a bit from
214 ;; MSB of dividend, we shift next bit of quotient in from carry
215 ;; HL holds remainder
216 ;; Do a 32-bit left shift, shifting carry to C, C to A,
218 rl c ; Carry (next bit of quotient) to bit 0
220 adc hl,hl ; HL < 32768 before, no carry, ever.
222 ;; If remainder is >= divisor, next bit of quotient is 1. This
225 jr NC,.nodrop ; Jump if remainder is >= dividend
226 add hl,de ; Otherwise, restore remainder
227 ;; The add above sets the carry, because sbc hl,de did set it.
229 ccf ; Complement borrow so 1 indicates a
230 ; successful substraction (this is the
231 ; next bit of quotient)
233 ;; Shift last carry bit into quotient
234 ex de,hl ; DE = remainder, HL = divisor...
235 ;; HL does not contain remainder, it contains the divisor!
236 ; ld d,h ; DE = remainder
240 ld b,a ; BC = quotient
241 ;; Carry now contains the same value it contained before
242 ;; entering .dvloop[*]: "0" = valid result.