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 JR 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 JR 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 JR 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 JR NZ,.divide ; Branch if divisor is non-zero
272 LD BC,#0x00 ; Divide by zero error
275 SCF ; Set carry, invalid result
278 LD L,C ; L = low byte of dividend/quotient
279 LD H,B ; H = high byte of dividend/quotient
280 LD BC,#0x00 ; BC = remainder
281 OR A ; Clear carry to start
282 LD A,#16 ; 16 bits in dividend
284 ;; Shift next bit of quotient into bit 0 of dividend
285 ;; Shift next MSB of dividend into LSB of remainder
286 ;; BC holds both dividend and quotient. While we shift a bit from
287 ;; MSB of dividend, we shift next bit of quotient in from carry
288 ;; HL holds remainder
289 ;; Do a 32-bit left shift, shifting carry to L, L to H,
292 RL L ; Carry (next bit of quotient) to bit 0
293 RL H ; Shift remaining bytes
295 RL B ; Clears carry since BC was 0
296 ;; If remainder is >= divisor, next bit of quotient is 1. This
298 PUSH BC ; Save current remainder
299 LD A,C ; Substract divisor from remainder
305 CCF ; Complement borrow so 1 indicates a
306 ; successful substraction (this is the
307 ; next bit of quotient)
308 JR C,.drop ; Jump if remainder is >= dividend
309 POP BC ; Otherwise, restore remainder
316 DEC A ; DEC does not affect carry flag
318 ;; Shift last carry bit into quotient
319 LD D,B ; DE = remainder
322 LD C,L ; C = low byte of quotient
324 LD B,H ; B = high byte of quotient
325 OR A ; Clear carry, valid result
331 .ds 0x01 ; Sign of quotient
333 .ds 0x01 ; Sign of remainder
335 .ds 0x01 ; Counter for division