I am trying to write a function that returns 0 if an overflow occurs and 1 otherwise. I am limited to bitwise functions, there is no casting and ints are always 32 bit.
I seem to be running into issues where addOK(0x80000000,0x80000001) returns 1 instead of 0 and I assume it's because notsum = !(x + y) does not equal 0. I'm not sure how to go about fixing this. Any ideas?
/*
* addOK - Determine if can compute x+y without overflow
* Example: addOK(0x80000000,0x80000000) = 0,
* addOK(0x80000000,0x70000000) = 1,
* addOK(0x80000000,0x80000001) = 0,
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 20
* Rating: 3
*/
int addOK(int x, int y) {
int notsum = !(x + y); // 0 if true, 1 if false
int mask = notsum + ~0; // ~0 is all 1s! overflow to 0s if notx is false
return (1 & mask) | (0 & ~mask); // mask is 1s if x is true
}