سؤال

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