Note that there are some explanatory texts on larger screens.

plurals
  1. POSaturated addition of two signed Java 'long' values
    primarykey
    data
    text
    <p>How can one add two <code>long</code> values in Java so that if the result overflows then it is clamped to the range <code>Long.MIN_VALUE</code>..<code>Long.MAX_VALUE</code>?</p> <p>For adding ints one can perform the arithmetic in <code>long</code> precision and cast the result back to an <code>int</code>, e.g.:</p> <pre><code>int saturatedAdd(int x, int y) { long sum = (long) x + (long) y; long clampedSum = Math.max((long) Integer.MIN_VALUE, Math.min(sum, (long) Integer.MAX_VALUE)); return (int) clampedSum; } </code></pre> <p>or</p> <pre><code>import com.google.common.primitives.Ints; int saturatedAdd(int x, int y) { long sum = (long) x + (long) y; return Ints.saturatedCast(sum); } </code></pre> <p>but in the case of <code>long</code> there is no larger primitive type that can hold the intermediate (unclamped) sum.</p> <p>Since this is Java, I cannot use <a href="https://stackoverflow.com/questions/121240/saturating-addition-in-c">inline assembly</a> (in particular SSE's saturated add instructions.)</p> <p>It can be implemented using <code>BigInteger</code>, e.g.</p> <pre><code>static final BigInteger bigMin = BigInteger.valueOf(Long.MIN_VALUE); static final BigInteger bigMax = BigInteger.valueOf(Long.MAX_VALUE); long saturatedAdd(long x, long y) { BigInteger sum = BigInteger.valueOf(x).add(BigInteger.valueOf(y)); return bigMin.max(sum).min(bigMax).longValue(); } </code></pre> <p>however performance is important so this method is not ideal (though useful for testing.)</p> <p>I don't know whether avoiding branching can significantly affect performance in Java. I assume it can, but I would like to benchmark methods both with and without branching.</p> <p>Related: <a href="https://stackoverflow.com/questions/121240/saturating-addition-in-c">How to do saturating addition in C?</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload