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