# Testing for exceeding the limits of a long

I am in a situation where I can not use unsigned long or any other variable type.
I must use long.
My problem is that I ran into a situation where I may have two extremly large long values that need to be added together with the result put into another long variable.
Example:
long x = 1178610030
long y = 1115152266
x + y = ?

I think a long has a limit of 2147483647 so if I add x + y my results are not what I should expect.
I actually get a negative number. This means I can't check to see if the result is larger than the limit of a long type.

Is there an easy way to check to see if the sum is larger than the limit of a long?
###### Who is Participating?

Commented:
You can get an extra bit out of things by using 'unsigned long' instead of long.

Performing Z = X + Y:
x >0 and y>0:  If z < x then overflow occurred
x > 0 and y <= 0:  no overflow is possible
x <=0 and y > 0:  no overflow is possible
x <= 0 and y <= 0:  if (z > x) then overflow occurred

Performing Z = X - Y:
x > 0 and y > 0:  no overflow is possible
x > 0 and y <= 0:  if z< x then overflow occurred
x <= 0 and y > 0:  if z > x then overflow occurred
x <= 0 and y <= 0:  if z < x then overflow occurred (only possible when x = 0 and y = -2^31)
0

Commented:
You could do something like:
if(x > 0 && y > 0 && (x + y) < 0)
{
// Error
}
The only way that the error could happen is if both numbers are positive and the sum is negative.  You could do bitmasking too, but this is probably more clean.
0

Author Commented:
So are you saying that the sum will always be a negative number?
0

Author Commented:
Thanks for the info.
0

Software ArchitectCommented:
You can use a 64 bit variable (like __int64) and test 31th or 32th bit.
Something like this:

__int64 x = 1178610030;
__int64 y = 1115152266;

__int64 result = x+y;
__int64 mask31 = ~((__int64) 0x7FFFFFFF);  // mask to detect if a bit past 31th is on

// error
}
0

Commented:
Actually, all those rules can be implemented like this:
long x,y,z;
bool overflow;

z = x+y;
overflow = (y <= 0 ? z > x : z < x);

z = x - y;
overflow = (y <= 0 ? z < x : z > x);
0

Author Commented:
Great. I appreciate it.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.