1

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
}
Chiara Lim
  • 11
  • 1
  • 2
    first you need to change to `unsigned int` for bitwise and arithmetic operations inside the function, because signed overflow is UB – phuclv Oct 25 '20 at 14:15
  • Plus: for unsigned overflow, the behaviour is simple: if the resulting sum is smaller than any of the operands, overflow (modulo resultsize) took place. – wildplasser Oct 25 '20 at 14:37

0 Answers0