Check port from long run in java

I add / substitute long type numbers. Is there any way to find out if the established theoretical hyphenation will be this operation?

+4
source share
2 answers

This should do:

/**
 * Add two long with overflow detection (r = s + d)
 */
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 , :

  • 63 1
  • 63 2
  • (0-62) 63

, :

long operand1 = ...
long operand2 = ...
long bitMask = Long.MAX_VALUE; // bits 0-62 set, bit 63 clear
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; // only bit 63 set, others clear
if ((a ^ flipSignBit) < (b ^ flipSignBit))
    System.out.println("borrow occurs");
+3

Java (Java SE 8) . :

  • = >
  • = > underflow
  • ,
  • sub: a - b = a + (-b)

, .

+1

Source: https://habr.com/ru/post/1545403/


All Articles