As part of a puzzle I am asked to implement a function which checks if two ints can be added together without overflow. Legal ops: ! ~ & ^ | + << >>.
For example for x = 0x80000000 and y = 0x80000000 the function should return 0 since it is overflowing but for x = 0x80000000 and y = 0x70000000 the result would be 1.
My solution so far is:
int addOK(int x, int y) {
int mask = ~(1 << 31); // 0x7fffffff
int newX = (mask & (x >> 1)); // Shift 1 to the right to make space for overflow bit
int newY = (mask & (y >> 1));
int add = newX + newY; // Add shifted x and y - overflow bit will be the MSB
int res = (add & ~mask); // Set all bits to 0 except MSB - MSB 1 iff overflow 0 otherwise
int endRes = !res; // 0x80000000 -> 0x00000000, 0x00000000 -> 0x00000001
printf("mask %x newX %x newY %x add %x ~mask %x res %x endRes %x\n",mask, newX, newY, add, ~mask, res, endRes);
return endRes;
}
The function prints the following for x = 0x80000000 and y = 0x80000000:
mask 7fffffff newX 40000000 newY 40000000 add 80000000 ~mask 80000000 res 0 endRes 1
Now my question is why is res
0? it should be 0x80000000 because both add
and ~mask
are 0x80000000. Can anyone explain this behavior to me?