Detecting overflow from addition

Jeremy Leach

Senior Member
Ok, how do you add two words together, and detect overflow from the addition when you don't have any carry flag? e.g
Code:
LSW = Word1 + Word2
Well the answer is so simple but it wasn't obvious to me until I worked it out! Maybe I'm thick, but the answer is : If LSW is less than any of Word1 or Word2 then there has been overflow. So can pick either of Word1 or Word2 and compare LSW to it. e.g
Code:
LSW = Word1 + Word2
If LSW < Word1 Then
	'Handle overflow
EndIf
Can easily see the principle by using base 10 ...

When no overflow, e.g 1 + 3 = 4, the answer is always >= both of the numbers being added (ok !!).

When overflow, the answer is always < any of the numbers being added.
e.g
1 + 9 = 0
5 + 7 = 2
 
Last edited:

Dippy

Moderator
Just keep the next patient waitng and have a go.
I often wondered why I have to wait so long at my local surgery :)
... and when I get in the PC screen suddenly minimises.
 

moxhamj

New Member
LOL dippy, 10am for you is 8pm here! I'm at home. And as well as living in your future, relative to you I'm also walking around upside down! Darned picaxes keep falling to the ceiling. Manuka is several hours ahead of me. I ring him when I am about to place a bet on a cricket match as he always knows the outcome.

And of course (slaps head in same way as Jeremy Leach did earlier), the answer with subraction a-b=c is to test if a<b before doing the subtraction. a>=b is no borrow, a<b is a borrow.
 
Last edited:

Jeremy Leach

Senior Member
Or, to test for borrow just basing it on the result: If c>a Then borrow has occured.

The addition one wasn't just for interest either. I'm using a double word to hold a large number and just wanted to add another word value to it - and suddenly hit this issue of how to detect carry when adding the two least significant words together.
 
Last edited:
Top