Search code examples
assemblyavratmega

Adding two 16 bit numbers using 8 bit registers (Assembly)


I need to add two 16 bit numbers using the instructions add and adc. The micro-controller I am using is an AtMega32 which has a max register size of 8 bits

This is what I tried so far, eg I am adding the numbers 5438 + 6098

.include "m32def.inc"
.org 0x0000

init:
ldi r16,54
ldi r17,38
ldi r18,60
ldi r19,98

start:
add r17,r19
adc r16,r18

rjmp init

If I add the lower bytes 38 and 98 = 136 which is an 8 bit number so it stores it perfectly fine with no carry but I want it to carry over so that I can add 54 and 60 with the carry to get 115. I dont know, maybe I am doing something wrong


Solution

  • You are confusing/mixing decimal and binary?

    Are you saying you want to add 5438 decimal with 6098 decimal? Which means you want to add 0x153E + 0x17D2. If so you add 0x3E + 0xD2 = 0x10 with a carry out then you add 0x15 + 0x17 + carry = 0x2D so the result is 0x2D10 = 11536 which is what you also get when you do the decimal addition on a calculator.

    If those are hex numbers 0x5438 + 0x6098 then you need to tell the assembler they are hex 0x54 or 54h or $54 whatever the syntax is for your assembler (0x54 should work).

    So in either case fix the immediate values and I think your program will work.