java check/detect integer/int/long overflow/underflow

look in jruby’s RubyFixnum.java for “additionOverflowed” and “subtractionOverflowed

    private static boolean additionOverflowed(long original, long other, long result) {
        return (~(original ^ other) & (original ^ result) & SIGN_BIT) != 0;
    }
    
    private static boolean subtractionOverflowed(long original, long other, long result) {
        return (~(original ^ ~other) & (original ^ result) & SIGN_BIT) != 0;
    }

One thought on “java check/detect integer/int/long overflow/underflow

  1. I’m reasonably certain that the test in subtractionOverflowed can be simplified from:
    return (~(original ^ ~other) & (original ^ result) & SIGN_BIT) != 0;
    to:
    return ((original ^ other) & (original ^ result) & SIGN_BIT) != 0;

    Proof (I hope):
    g h (g^h) ~ ( g ^ ~ h)
    0 0 0 0 0 1 1 0
    0 1 1 1 0 0 0 1
    1 0 1 1 1 0 1 0
    1 1 0 0 1 1 0 1

Leave a Reply

Your email address will not be published. Required fields are marked *


7 + = eleven

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>