1 ;; Originally from GBDK by Pascal Felber.
201 ; Fall through to .div16
212 ;; If divisor is non-zero, carry=0
213 ;; If divisor is 0, carry=1 and both quotient and remainder are 0
215 ;; Register used: AF,BC,DE,HL
218 ;; Determine sign of quotient by xor-ing high bytes of dividend
219 ;; and divisor. Quotient is positive if signs are the same, negative
220 ;; if signs are different
221 ;; Remainder has same sign as dividend
222 LD A,B ; Get high byte of dividend
223 LD (.srem),A ; Save as sign of remainder
224 XOR D ; Xor with high byte of divisor
225 LD (.squot),A ; Save sign of quotient
226 ;; Take absolute value of divisor
228 jp Z,.chkde ; Jump if divisor is positive
229 SUB A ; Substract divisor from 0
232 SBC A ; Propagate borrow (A=0xFF if borrow)
235 ;; Take absolute value of dividend
238 jp Z,.dodiv ; Jump if dividend is positive
239 SUB A ; Substract dividend from 0
242 SBC A ; Propagate borrow (A=0xFF if borrow)
245 ;; Divide absolute values
248 RET C ; Exit if divide by zero
249 ;; Negate quotient if it is negative
252 jp Z,.dorem ; Jump if quotient is positive
253 SUB A ; Substract quotient from 0
256 SBC A ; Propagate borrow (A=0xFF if borrow)
260 ;; Negate remainder if it is negative
263 RET Z ; Return if remainder is positive
264 SUB A ; Substract remainder from 0
267 SBC A ; Propagate remainder (A=0xFF if borrow)
276 ; Fall through to divu16
280 ;; Check for division by zero
283 jp NZ,.divide ; Branch if divisor is non-zero
284 LD BC,#0x00 ; Divide by zero error
287 SCF ; Set carry, invalid result
291 ; LD L,C ; L = low byte of dividend/quotient
292 ; LD H,B ; H = high byte of dividend/quotient
293 ; LD BC,#0x00 ; BC = remainder
294 OR A ; Clear carry to start
296 LD A,#16 ; 16 bits in dividend
298 ;; Shift next bit of quotient into bit 0 of dividend
299 ;; Shift next MSB of dividend into LSB of remainder
300 ;; BC holds both dividend and quotient. While we shift a bit from
301 ;; MSB of dividend, we shift next bit of quotient in from carry
302 ;; HL holds remainder
303 ;; Do a 32-bit left shift, shifting carry to L, L to H,
306 RL C ; Carry (next bit of quotient) to bit 0
307 RL B ; Clears carry since BC was 0
310 ;; If remainder is >= divisor, next bit of quotient is 1. This
312 PUSH HL ; Save current remainder
314 ; LD A,C ; Substract divisor from remainder
320 CCF ; Complement borrow so 1 indicates a
321 ; successful substraction (this is the
322 ; next bit of quotient)
323 jp C,.drop ; Jump if remainder is >= dividend
324 POP HL ; Otherwise, restore remainder
331 DEC A ; DEC does not affect carry flag
334 ;; Shift last carry bit into quotient
335 LD D,H ; DE = remainder
338 ; LD C,L ; C = low byte of quotient
340 ; LD B,H ; B = high byte of quotient
341 OR A ; Clear carry, valid result
347 .ds 0x01 ; Sign of quotient
349 .ds 0x01 ; Sign of remainder
351 .ds 0x01 ; Counter for division