質問

if I add or subtract two short values, how can I tell if I would need to flag a carry condition

役に立ちましたか?

解決

In the case of adding and subtracting only, arithmetic overflow has occurred when both operands are positive and the result is negative and vice versa.

class OverflowTest
{
        public static void main (String[] args)
        {
                System.out.println(isOverflow((short)32767, (short)32767, '+'));
                System.out.println(isOverflow((short)-32767, (short)-32767, '+'));
                System.out.println(isOverflow((short)32767, (short)-32767, '+'));       
        }

        private static boolean isOverflow(short a, short b, char op) {  
                short c = (op == '+') ? (short)(a+b) : (short)(a-b);
                if((a > 0 && b > 0 && c < 0) || (a < 0 && b < 0 && c > 0))
                        return true;
                return false;
        }
}

他のヒント

You can do the addition or subtraction using a larger type such as int, cast it to a short, and test if the cast changes the value.

int i = s1 + s2;
short s = (short)i;
if (i != s) { /* overflow */ }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top