0

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

Chris Camacho
  • 1,164
  • 1
  • 9
  • 31

2 Answers2

3

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 */ }
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Actually *any* arithmetic operation on smaller than int values is extended to int anyhow, so we don't need the int casts there. – Voo Apr 29 '12 at 00:08
  • 1
    carry and overflow are two different things!!! http://www.piclist.com/techref/method/math/c-vs-o.htm – Chris Camacho Apr 30 '12 at 15:51
0

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;
        }
}
blackcompe
  • 3,180
  • 16
  • 27
  • The textual explanation is ok, but I really can't follow your code example there. – Voo Apr 29 '12 at 00:08
  • @Voo: What don't you understand? – blackcompe Apr 29 '12 at 00:40
  • Well I'd either omit the example or provide a general one. But something that only works when both values are positive? That probably causes more confusion I'd think. – Voo Apr 29 '12 at 09:30
  • This is a valid solution to set the overflow flag, but **not the carry flag** as asked in the question! – CodeZombie Nov 03 '13 at 02:23