There is no "add with carry" instruction on PIC 16. But what if I had to add larger data quantity than just a byte? All the Web resources and Microchip application notes I've found suggest something like:
MOVF LSB_A, w
ADDWF LSB_B
MOVF MSB_A, w
BTFSC STATUS, C
INCFSZ MSB_A, w
ADDWF MSB_B
but the code above will just not work. I mean the 16-bit result will be correct, but the carry won't be set properly, so you can't just expand the computational range by repeating the second part of the code above. Am I right so far?
Below is my implementation of addition with carry:
MOVF BYTE1, w
BTFSC STATUS, C
ADDLW 1
RLF TEMP ; save the carry
ADDWF BYTE2
BTFSS STATUS, C
RRF TEMP ; restore the carry (from the first addition)
You can use plain addition for the least significant byte or clear the carry before using a sequence of additions with carry.
I guess it works, but are there more effective solutions to this problem?
Microchip's Code Module Library (CML) gives the following snippet for 16-bit addition, which does seem to cope with the overflow situation you describe (too large for a comment so I hope you'll forgive me posting as an answer) :
; Snippet: 16-bit A+B
;
; Inputs: A_high, A_low, B_high, B_low
; Outputs: RES_high, RES_low
movf A_low, W
addwf B_low, W
movwf RES_low ; Result in RES_low
movlw 0x00 ; Clear W
btfsc STATUS, C
movlw 0x01 ; C=1, carry present. Set W to add 1 to high bytes.
; C=0, there was no carry from low byte to high byte
addwf A_high, W ; Add A_high to W (either 0, or 1 if carry)
btfsc STATUS, C ; Check for o/f when adding low carry
goto early_overflow ; if don't check here, A_high = 0xFF will miss high byte carry
addwf B_high, W ; Add B_high to above
movwf RES_high ; Result in RES_high
btfss STATUS, C ; Check whole 16-bit addition for carry
goto end_add16 ; C=0, result valid
goto overflow ; C=1, result overflowed
early_overflow:
addwf B_high, W ; Add B_high to A_high + carry
movwf RES_high ; Result in RES_high
overflow:
; Can place code here to handle
; what to do in case result overflowed.
end_add16: ; end of snippet