문제

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