加带进PIC16(或类似器件) [英] Adding with carry on PIC16 (or similar)
问题描述
在PIC 16上没有随身携带加"指令.但是,如果我必须增加比一个字节大的数据量该怎么办?我发现的所有Web资源和Microchip应用笔记都建议类似以下内容:
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
,但是上面的代码将不起作用.我的意思是16位结果将是正确的,但是进位设置不正确,因此您不能仅通过重复上面代码的第二部分来扩展计算范围.我到目前为止正确吗?
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的代码模块库(CML)为16位加法提供了以下代码段,该代码段似乎可以应付您所描述的溢出情况(对于发表评论,希望您能原谅我的回答):
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
这篇关于加带进PIC16(或类似器件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!