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