1 ;; Originally from GBDK by Pascal Felber.
264 ; Fall through to .div16
275 ;; If divisor is non-zero, carry=0
276 ;; If divisor is 0, carry=1 and both quotient and remainder are 0
278 ;; Register used: AF,BC,DE,HL
281 ;; Determine sign of quotient by xor-ing high bytes of dividend
282 ;; and divisor. Quotient is positive if signs are the same, negative
283 ;; if signs are different
284 ;; Remainder has same sign as dividend
285 ld a,b ; Get high byte of dividend
286 push af ; Save as sign of remainder
287 xor d ; Xor with high byte of divisor
288 push af ; Save sign of quotient
290 ;; Take absolute value of divisor
292 jr Z,.chkde ; Jump if divisor is positive
293 sub a ; Substract divisor from 0
296 sbc a ; Propagate borrow (A=0xFF if borrow)
299 ;; Take absolute value of dividend
302 jr Z,.dodiv ; Jump if dividend is positive
303 sub a ; Substract dividend from 0
306 sbc a ; Propagate borrow (A=0xFF if borrow)
309 ;; Divide absolute values
312 jr C,.exit ; Exit if divide by zero
313 ;; Negate quotient if it is negative
314 pop af ; recover sign of quotient
316 jr Z,.dorem ; Jump if quotient is positive
317 sub a ; Substract quotient from 0
320 sbc a ; Propagate borrow (A=0xFF if borrow)
324 ;; Negate remainder if it is negative
325 pop af ; recover sign of remainder
327 ret Z ; Return if remainder is positive
328 sub a ; Substract remainder from 0
331 sbc a ; Propagate remainder (A=0xFF if borrow)
344 ; Fall through to divu16
348 ;; Check for division by zero
351 jr NZ,.divide ; Branch if divisor is non-zero
352 ld bc,#0x00 ; Divide by zero error
355 scf ; Set carry, invalid result
359 ; ld l,c ; L = low byte of dividend/quotient
360 ; ld h,b ; H = high byte of dividend/quotient
361 ; ld bc,#0x00 ; BC = remainder
362 or a ; Clear carry to start
364 ld a,#16 ; 16 bits in dividend
366 ;; Shift next bit of quotient into bit 0 of dividend
367 ;; Shift next MSB of dividend into LSB of remainder
368 ;; BC holds both dividend and quotient. While we shift a bit from
369 ;; MSB of dividend, we shift next bit of quotient in from carry
370 ;; HL holds remainder
371 ;; Do a 32-bit left shift, shifting carry to L, L to H,
374 rl c ; Carry (next bit of quotient) to bit 0
375 rl b ; Clears carry since BC was 0
378 ;; If remainder is >= divisor, next bit of quotient is 1. This
380 push hl ; Save current remainder
382 ; ld a,c ; Substract divisor from remainder
388 ccf ; Complement borrow so 1 indicates a
389 ; successful substraction (this is the
390 ; next bit of quotient)
391 jr C,.drop ; Jump if remainder is >= dividend
392 pop hl ; Otherwise, restore remainder
399 dec a ; DEC does not affect carry flag
402 ;; Shift last carry bit into quotient
403 ld d,h ; DE = remainder
406 ; ld c,l ; C = low byte of quotient
408 ; ld b,h ; B = high byte of quotient
409 or a ; Clear carry, valid result