SUB_DIVIDE_24B_BY_16B ;=============================== DIVIDE ROUTINE
clrf REM0
clrf REM1
movlw 0x18
movwf TEMP_MAIN_LOOP_01
LOOPU2416
rlcf AARG0, W ;shift dividend left to move next bit to remainder
rlcf AARG1, F
rlcf AARG2, F
rlcf REM0, F ;shift carry (next dividend bit) into remainder
rlcf REM1, F
rlcf AARG0, F
;finish shifting the dividend and save carry in AARG0.0,
;since remainder can be 17 bit long in some cases
;(e.g. 0x800000/0xFFFF). This bit will also serve
;as the next result bit.
movf BARG0, W ;substract divisor from 16-bit remainder
subwf REM0, F
movf BARG1, W
btfss STATUS, C
incfsz BARG1, W
subwf REM1, F
; Here we also need to take into account the 17th bit of the remainder, which is in AARG0.0.
; If we don't have a borrow after subtracting from the lower 16 bits of the remainder,
; then there is no borrow regardless of 17th bit value.
; But, if we have the borrow, then that will depend on the 17th bit value.
; If it is 1, then no final borrow will occur.
; If it is 0, then a borrow will occur.
; These values match the borrow flag polarity.
btfsc STATUS, C ;SKPNC
bsf AARG0, 0
; If no borrow after 16 bit subtraction then there is no borrow in result.
; Overwrite AARGB2.0 with 1 to indicate no borrow.
; If a borrow did occur, AARGB2.0 already holds the final borrow value (0-borrow, 1-no borrow)
btfsc AARG0, 0 ;if no borrow after 17-bit subtraction
goto UOK46LL ;skip remainder restoration.
addwf REM1, F
;restore higher byte of remainder. (w contains the value subtracted from it previously)
movf BARG0, W ;restore lower byte of remainder
addwf REM0, F
UOK46LL
decfsz TEMP_MAIN_LOOP_01, f ;decrement counter
goto LOOPU2416 ;and repeat the loop if not zero.
return