1 ;; Originally from GBDK by Pascal Felber.
129 ; Fall through to .div16
140 ;; If divisor is non-zero, carry=0
141 ;; If divisor is 0, carry=1 and both quotient and remainder are 0
143 ;; Register used: AF,BC,DE,HL
146 ;; Determine sign of quotient by xor-ing high bytes of dividend
147 ;; and divisor. Quotient is positive if signs are the same, negative
148 ;; if signs are different
149 ;; Remainder has same sign as dividend
150 LD A,B ; Get high byte of dividend
151 LD (.srem),A ; Save as sign of remainder
152 XOR D ; Xor with high byte of divisor
153 LD (.squot),A ; Save sign of quotient
154 ;; Take absolute value of divisor
156 jp Z,.chkde ; Jump if divisor is positive
157 SUB A ; Substract divisor from 0
160 SBC A ; Propagate borrow (A=0xFF if borrow)
163 ;; Take absolute value of dividend
166 jp Z,.dodiv ; Jump if dividend is positive
167 SUB A ; Substract dividend from 0
170 SBC A ; Propagate borrow (A=0xFF if borrow)
173 ;; Divide absolute values
176 RET C ; Exit if divide by zero
177 ;; Negate quotient if it is negative
180 jp Z,.dorem ; Jump if quotient is positive
181 SUB A ; Substract quotient from 0
184 SBC A ; Propagate borrow (A=0xFF if borrow)
188 ;; Negate remainder if it is negative
191 RET Z ; Return if remainder is positive
192 SUB A ; Substract remainder from 0
195 SBC A ; Propagate remainder (A=0xFF if borrow)
204 ; Fall through to divu16
208 ;; Check for division by zero
211 jp NZ,.divide ; Branch if divisor is non-zero
212 LD BC,#0x00 ; Divide by zero error
215 SCF ; Set carry, invalid result
219 ; LD L,C ; L = low byte of dividend/quotient
220 ; LD H,B ; H = high byte of dividend/quotient
221 ; LD BC,#0x00 ; BC = remainder
222 OR A ; Clear carry to start
224 LD A,#16 ; 16 bits in dividend
226 ;; Shift next bit of quotient into bit 0 of dividend
227 ;; Shift next MSB of dividend into LSB of remainder
228 ;; BC holds both dividend and quotient. While we shift a bit from
229 ;; MSB of dividend, we shift next bit of quotient in from carry
230 ;; HL holds remainder
231 ;; Do a 32-bit left shift, shifting carry to L, L to H,
234 RL C ; Carry (next bit of quotient) to bit 0
235 RL B ; Clears carry since BC was 0
238 ;; If remainder is >= divisor, next bit of quotient is 1. This
240 PUSH HL ; Save current remainder
242 ; LD A,C ; Substract divisor from remainder
248 CCF ; Complement borrow so 1 indicates a
249 ; successful substraction (this is the
250 ; next bit of quotient)
251 jp C,.drop ; Jump if remainder is >= dividend
252 POP HL ; Otherwise, restore remainder
259 DEC A ; DEC does not affect carry flag
262 ;; Shift last carry bit into quotient
263 LD D,H ; DE = remainder
266 ; LD C,L ; C = low byte of quotient
268 ; LD B,H ; B = high byte of quotient
269 OR A ; Clear carry, valid result
275 .ds 0x01 ; Sign of quotient
277 .ds 0x01 ; Sign of remainder
279 .ds 0x01 ; Counter for division