This should do:
public static long add(final long s, final long d){
final long r = s + d;
if (((s & d & ~r) | (~s & ~d & r)) < 0)
throw new RuntimeException("long overflow add(" + s + ", " + d + ")");
return r;
}
This was asked here: How does Java handle an integer with overflow and overflow, and how do you check it? (Subtraction is also described here)
: , OP , . - " () 64- , 64 (, 0 = LSB 63 = MSB )"
, 64 , :
, :
long operand1 = ...
long operand2 = ...
long bitMask = Long.MAX_VALUE;
int conditions = 0;
if (operand1 < 0)
++conditions;
if (operand2 < 0)
++conditions;
if (((operand1 & bitMask) + (operand2 & bitMask)) < 0)
++conditions;
if (conditions > 1)
System.out.println("carry would be set!");
, , , .
: (a - b), b , a. , java :
long flipSignBit = Long.MIN_VALUE;
if ((a ^ flipSignBit) < (b ^ flipSignBit))
System.out.println("borrow occurs");