The MASM Forum
General => The Campus => Topic started by: DanWebb314 on June 09, 2012, 03:32:37 AM
-
How can I add two unsigned integers? 'ADD' uses signed addition. Is there an instruction to do an unsigned add?
-
same instruction
that is the nature of two's compliment
be aware that if you add 2 unsigned values, and the result is larger than the register, it will set the carry flag
if the result fits in the register, the carry flag will be cleared
-
As dedndave says, the same instruction is used. The difference is in the flags that should be used to interpret the result:
When an unsigned addition overflows (MSB goes from 1 to 0) or an unsigned subtraction underflows (MSB goes from 0 to 1), the carry flag (CF) is set.
The JC/JNC instructions let you branch based on this, as do JA/JAE/JB/JBE ("above" or "below" when you've used SUB or CMP).
When a signed addition overflows (MSB goes from 0 to 1) or a signed subtraction underfloms (MSB goes from 1 to 0) the overflow flag (OF) is set.
The JO/JNO instructions let you branch based on this, as do JG/JGE/JL/JLE ("greater" or "less" when you've used SUB or CMP).
Two's complement enables an identical representation to be used for signed and unsigned integers, and identical electronics to implement addition and subtraction (but not multiplication and division).
Cheers,
Zooba :t
-
Very helpful
Thank you
-
DanWebb314,
Note that you can use the same two instructions (add and sub along with two others) to do 64 bit arithmetic:
.data
FirstLow dd 12345678h
FirstHigh dd 87654321h
SecindLow dd 01111111h
SecindHigh dd 00111111h
.code
mov eax,FirstLow
mov ebx,FirstHigh
mov ecx,SecondLow
mov edx,SecondHigh
;
; to add
;
add eax,ecx ; Causes a possible carry
adc ebx,edx ; Adds the two numbers plus the possible carry.
;
; to subtract
;
sub eax,ecx ; Causes a possible borrow
sbb ebx,edx ; subtracts the two numbers and a possible borrow.
;
; eax ebx should be same as FirstLow and FirstHigh
;
Dave.
-
Cool!
-
You can increment a 64 bit number by:
add FirstLow,1
awc FirstHigh,0
Dave.
-
awc FirstHigh,0
Typo, it should be adc aka add with carry. Note it won't work with inc FirstLow because inc does not set the carry flag.
-
Jochen,
Thank you for catching that, don't want to propagate bad code.
Dave.
-
...don't want to propagate bad code.
Don't worry, ML.exe would have stopped you with a nasty error message :biggrin:
But the inc thing is worth remembering - I think the other Dave pushed me onto that one a long time ago :P