Question

I have a few questions about instructions in asm

1) add Rd, Rr; Are Rd and Rr unsigned or signed numbers?

2) How to load signed numer in register? i know that LDI Rd,K is loading unisgned.

3) Can you provide me with concrete example with adding two 16bit numbers, and is it poisable that one number is negative?

Was it helpful?

Solution

The nice thing about 2's complement arithmetic is that addition and subtraction work the same no matter whether the operands are signed or not. It's up to the programmer to interpret the operands and the result appropriately. Detecting overflow is different though.

Let's add 12345 and -10. 12345 is 0x3039 and -10 is 0xfff6. We'll just add the low bytes first, then the high bytes with the carry from the first operation.

LDI R16, 0x39 ; low byte of 12345
LDI R17, 0x30 ; high byte of 12345
LDI R18, 0xf6 ; low byte of -10
LDI R19, 0xff ; high byte of -10
ADD R16, R18   ; add low bytes without carry
; R16 is now 0x39 + 0xf6 = 0x2f and carry is 1
ADC R17, R19   ; add high bytes and the carry
; R17 is now 0x30 + 0xff + 0x01 = 0x30

So, the result is 0x302f which is 12335 and is the expected value. Now, we could consider the initial -10 to be the unsigned number 65526, the result would still be correct without any change, but in this case we'd have an overflow (wrap around).

You can read about 2's complement on wikipedia.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top