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 ld (.srem),a ; Save as sign of remainder
212 xor d ; Xor with high byte of divisor
213 ld (.squot),a ; Save sign of quotient
214 ;; Take absolute value of divisor
216 jp Z,.chkde ; Jump if divisor is positive
217 sub a ; Substract divisor from 0
220 sbc a ; Propagate borrow (A=0xFF if borrow)
223 ;; Take absolute value of dividend
226 jp Z,.dodiv ; Jump if dividend is positive
227 sub a ; Substract dividend from 0
230 sbc a ; Propagate borrow (A=0xFF if borrow)
233 ;; Divide absolute values
236 ret C ; Exit if divide by zero
237 ;; Negate quotient if it is negative
240 jp Z,.dorem ; Jump if quotient is positive
241 sub a ; Substract quotient from 0
244 sbc a ; Propagate borrow (A=0xFF if borrow)
248 ;; Negate remainder if it is negative
251 ret Z ; Return if remainder is positive
252 sub a ; Substract remainder from 0
255 sbc a ; Propagate remainder (A=0xFF if borrow)
264 ; Fall through to divu16
268 ;; Check for division by zero
271 jp NZ,.divide ; Branch if divisor is non-zero
272 ld bc,#0x00 ; Divide by zero error
275 scf ; Set carry, invalid result
279 ; ld l,c ; L = low byte of dividend/quotient
280 ; ld h,b ; H = high byte of dividend/quotient
281 ; ld bc,#0x00 ; BC = remainder
282 or a ; Clear carry to start
284 ld a,#16 ; 16 bits in dividend
286 ;; Shift next bit of quotient into bit 0 of dividend
287 ;; Shift next MSB of dividend into LSB of remainder
288 ;; BC holds both dividend and quotient. While we shift a bit from
289 ;; MSB of dividend, we shift next bit of quotient in from carry
290 ;; HL holds remainder
291 ;; Do a 32-bit left shift, shifting carry to L, L to H,
294 rl c ; Carry (next bit of quotient) to bit 0
295 rl b ; Clears carry since BC was 0
298 ;; If remainder is >= divisor, next bit of quotient is 1. This
300 push hl ; Save current remainder
302 ; ld a,c ; Substract divisor from remainder
308 ccf ; Complement borrow so 1 indicates a
309 ; successful substraction (this is the
310 ; next bit of quotient)
311 jp C,.drop ; Jump if remainder is >= dividend
312 pop hl ; Otherwise, restore remainder
319 dec a ; DEC does not affect carry flag
322 ;; Shift last carry bit into quotient
323 ld d,h ; DE = remainder
326 ; ld c,l ; C = low byte of quotient
328 ; ld b,h ; B = high byte of quotient
329 or a ; Clear carry, valid result
335 .ds 0x01 ; Sign of quotient
337 .ds 0x01 ; Sign of remainder
339 .ds 0x01 ; Counter for division