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.
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?
NovaDenizenConnect With a Mentor Commented:
You can get an extra bit out of things by using 'unsigned long' instead of long.

If unsigned long won't help you, then here are some basic rules for additive overflow.

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)
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.
mcravenufoAuthor Commented:
So are you saying that the sum will always be a negative number?
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

mcravenufoAuthor Commented:
Thanks for the info.
Jaime OlivaresSoftware 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

if (result & mask31) {
    // error
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);
mcravenufoAuthor Commented:
Great. I appreciate it.
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.

All Courses

From novice to tech pro — start learning today.