1 ;; Originally from GBDK by Pascal Felber.
189 ; Fall through to .div16
200 ;; If divisor is non-zero, carry=0
201 ;; If divisor is 0, carry=1 and both quotient and remainder are 0
203 ;; Register used: AF,BC,DE,HL
206 ;; Determine sign of quotient by xor-ing high bytes of dividend
207 ;; and divisor. Quotient is positive if signs are the same, negative
208 ;; if signs are different
209 ;; Remainder has same sign as dividend
210 ld a,b ; Get high byte of dividend
211 push af ; Save as sign of remainder
212 xor d ; Xor with high byte of divisor
213 push af ; Save sign of quotient
215 ;; Take absolute value of divisor
217 jr Z,.chkde ; Jump if divisor is positive
218 sub a ; Substract divisor from 0
221 sbc a ; Propagate borrow (A=0xFF if borrow)
224 ;; Take absolute value of dividend
227 jr Z,.dodiv ; Jump if dividend is positive
228 sub a ; Substract dividend from 0
231 sbc a ; Propagate borrow (A=0xFF if borrow)
234 ;; Divide absolute values
237 jr C,.exit ; Exit if divide by zero
238 ;; Negate quotient if it is negative
239 pop af ; recover sign of quotient
241 jr Z,.dorem ; Jump if quotient is positive
242 sub a ; Substract quotient from 0
245 sbc a ; Propagate borrow (A=0xFF if borrow)
249 ;; Negate remainder if it is negative
250 pop af ; recover sign of remainder
252 ret Z ; Return if remainder is positive
253 sub a ; Substract remainder from 0
256 sbc a ; Propagate remainder (A=0xFF if borrow)
269 ; Fall through to divu16
273 ;; Check for division by zero
276 jr NZ,.divide ; Branch if divisor is non-zero
277 ld bc,#0x00 ; Divide by zero error
280 scf ; Set carry, invalid result
284 ; ld l,c ; L = low byte of dividend/quotient
285 ; ld h,b ; H = high byte of dividend/quotient
286 ; ld bc,#0x00 ; BC = remainder
287 or a ; Clear carry to start
289 ld a,#16 ; 16 bits in dividend
291 ;; Shift next bit of quotient into bit 0 of dividend
292 ;; Shift next MSB of dividend into LSB of remainder
293 ;; BC holds both dividend and quotient. While we shift a bit from
294 ;; MSB of dividend, we shift next bit of quotient in from carry
295 ;; HL holds remainder
296 ;; Do a 32-bit left shift, shifting carry to L, L to H,
299 rl c ; Carry (next bit of quotient) to bit 0
300 rl b ; Clears carry since BC was 0
303 ;; If remainder is >= divisor, next bit of quotient is 1. This
305 push hl ; Save current remainder
307 ; ld a,c ; Substract divisor from remainder
313 ccf ; Complement borrow so 1 indicates a
314 ; successful substraction (this is the
315 ; next bit of quotient)
316 jr C,.drop ; Jump if remainder is >= dividend
317 pop hl ; Otherwise, restore remainder
324 dec a ; DEC does not affect carry flag
327 ;; Shift last carry bit into quotient
328 ld d,h ; DE = remainder
331 ; ld c,l ; C = low byte of quotient
333 ; ld b,h ; B = high byte of quotient
334 or a ; Clear carry, valid result