How can I do this in AVR assembly?
I have 2 numbers (Little endian) in different reg.
# Number 1
LDI R16 0x…
LDI R17 0x…
LDI R18 0x…
LDI R19 0x…
# Number 2
LDI R20 0x…
LDI R21 0x…
LDI R22 0x…
LDI R23 0x…
I want to add them together and save the result to R20 – R23.
Regarding the “math” behind it: It’s just the same as in the decimal system:
When adding two single digit numbers, two cases have to be considered. Either the sum of the two is a new single digit number (5+4 = 9), or an ‘overflow’ occurs and another digit is required (5+6 = 11). Note that for any two numbers (in any base, be it 10, 2, 256 or whatever) of
ndigits length the sum of the two will always be lower than two times the lowest number ofn+1digits length; letiandjbe numbers (base 10) of, e.g., length 1, that is, both are between0and9, inclusive. As10is the lowest number of lengthn+1 = 2, their sum will always be lower than2 x 10.When adding two numbers, there may be no overflow or there may be an overflow of exactly 1. The carry bit stores this overflow from the last arithmetic operation; it’s either 0 or 1.
So, when adding your two numbers of 4x 8 bit each (which can be seen as 4 ‘digits’ base 256), there will be no overflow to be considered for the first addition, hence only
ADD;ADDcan be regarded as an operation forx = x + y + 0. After the first addition however there may be an overflow which needs to be taken into account, which is done by usingADDC;ADDCrepresents the operation ofx = x + y + carry, wherecarrycan only be 0 or 1 as mentioned above. After all digits have been added, the last addition may have caused an overflow again which will be reflected in the carry bit afterwards and can be evaluated to possibly react to the overflow of the numberrange, like: