1 ;; Originally from GBDK by Pascal Felber.
113 ; Fall through to __div16
124 ;; If divisor is non-zero, carry=0
125 ;; If divisor is 0, carry=1 and both quotient and remainder are 0
127 ;; Register used: AF,BC,DE,HL
130 ;; Determine sign of quotient by xor-ing high bytes of dividend
131 ;; and divisor. Quotient is positive if signs are the same, negative
132 ;; if signs are different
133 ;; Remainder has same sign as dividend
134 ld a,b ; Get high byte of dividend
135 push af ; Save as sign of remainder
136 xor d ; Xor with high byte of divisor
137 push af ; Save sign of quotient
139 ;; Take absolute value of divisor
141 jr Z,.chkde ; Jump if divisor is positive
142 sub a ; Substract divisor from 0
145 sbc a ; Propagate borrow (A=0xFF if borrow)
148 ;; Take absolute value of dividend
151 jr Z,.dodiv ; Jump if dividend is positive
152 sub a ; Substract dividend from 0
155 sbc a ; Propagate borrow (A=0xFF if borrow)
158 ;; Divide absolute values
161 jr C,.exit ; Exit if divide by zero
162 ;; Negate quotient if it is negative
163 pop af ; recover sign of quotient
165 jr Z,.dorem ; Jump if quotient is positive
166 sub a ; Substract quotient from 0
169 sbc a ; Propagate borrow (A=0xFF if borrow)
173 ;; Negate remainder if it is negative
174 pop af ; recover sign of remainder
176 ret Z ; Return if remainder is positive
177 sub a ; Substract remainder from 0
180 sbc a ; Propagate remainder (A=0xFF if borrow)
193 ; Fall through to divu16
197 ;; Check for division by zero
200 jr NZ,.divide ; Branch if divisor is non-zero
201 ld bc,#0x00 ; Divide by zero error
204 scf ; Set carry, invalid result
208 ; ld l,c ; L = low byte of dividend/quotient
209 ; ld h,b ; H = high byte of dividend/quotient
210 ; ld bc,#0x00 ; BC = remainder
211 or a ; Clear carry to start
213 ld a,#16 ; 16 bits in dividend
215 ;; Shift next bit of quotient into bit 0 of dividend
216 ;; Shift next MSB of dividend into LSB of remainder
217 ;; BC holds both dividend and quotient. While we shift a bit from
218 ;; MSB of dividend, we shift next bit of quotient in from carry
219 ;; HL holds remainder
220 ;; Do a 32-bit left shift, shifting carry to L, L to H,
223 rl c ; Carry (next bit of quotient) to bit 0
224 rl b ; Clears carry since BC was 0
227 ;; If remainder is >= divisor, next bit of quotient is 1. This
229 push hl ; Save current remainder
231 ; ld a,c ; Substract divisor from remainder
237 ccf ; Complement borrow so 1 indicates a
238 ; successful substraction (this is the
239 ; next bit of quotient)
240 jr C,.drop ; Jump if remainder is >= dividend
241 pop hl ; Otherwise, restore remainder
248 dec a ; DEC does not affect carry flag
251 ;; Shift last carry bit into quotient
252 ld d,h ; DE = remainder
255 ; ld c,l ; C = low byte of quotient
257 ; ld b,h ; B = high byte of quotient
258 or a ; Clear carry, valid result