-1

I have to make functions that check for overflow in integer addition, subtraction, and unsigned int addition(using only ! ~ | & ^ + >> <<). I have functions figured out for signed integer addition and subtraction, but I can't figure out how to do one for unsigned int addition.

How would I go about doing this?

Here is the code I have for the 2 functions I have completed:

int twosAddOk(int x, int y){
    int z=x+y;
    int a=x>>31;
    int b=y>>31;
    int c=z>>31;
    return !!(a^b)|(!(a^c)&!(b^c));
}

int twosSubtractOK(int x, int y){
    int z=x+~y+1;
    return !(((x^y & x^z))>>31);
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
ians
  • 11
  • 1

2 Answers2

0

You can calculate the carry-out from the MSB the hard way:

int unsignedAddOk(unsigned int x, unsigned int y){

    unsigned int x0=(~(1U<<31))&x; // MSB of x cleared
    unsigned int y0=(~(1U<<31))&y; // MSB of y cleared
    int c=(x0+y0)>>31; // Carry-in of MSB
    int a=x>>31; // MSB of x
    int b=y>>31; // MSB of y
    return !((a&b)|(a&c)|(b&c));
}
mkayaalp
  • 2,631
  • 10
  • 17
0

Perhaps a solution without coding the magic number 31

// Return 1 on overflow
int unsigned_add_overflow_test(unsigned a, unsigned b) {
  // Add all but the LSBits and then add 1 if both LSBits are 1
  // When overflow would occur with a + b, sum's MSBit is set.
  unsigned sum = (a >> 1) + (b >> 1) + (a&b&1);
  // Test MSBit set
  //                vvv--------- All bits set
  return !!(sum & ~(-1u >> 1));
  //               ^^^^^^^^^^ -- All bits set, except MSBit
  //              ^^^^^^^^^^^ -- MSBit set, rest are 0 
}

Or as a one-liner

!!( ((a >> 1) + (b >> 1) + (a&b&1)) & ~(-1u >> 1)) )
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256