News:

Masm32 SDK description, downloads and other helpful links
Message to All Guests
NB: Posting URL's See here: Posted URL Change

Main Menu

unsigned add

Started by DanWebb314, June 09, 2012, 03:32:37 AM

Previous topic - Next topic

DanWebb314

How can I add two unsigned integers?  'ADD' uses signed addition.  Is there an instruction  to do an unsigned add?

dedndave

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

zooba

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

DanWebb314

Very helpful
Thank you

KeepingRealBusy

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.

DanWebb314


KeepingRealBusy

You can increment a 64 bit number by:


    add    FirstLow,1
    awc    FirstHigh,0


Dave.

jj2007

Quote from: KeepingRealBusy on June 13, 2012, 09:15:20 AM
    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.

KeepingRealBusy

Jochen,

Thank you for catching that, don't want to propagate bad code.

Dave.

jj2007

Quote from: KeepingRealBusy on June 14, 2012, 12:48:29 AM
...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