-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);
}
11
  • 2
    Please show the code for the checks you have so far. Commented Apr 5, 2021 at 20:48
  • 1
    @Barmar Looks like it will violate the constraints Commented Apr 5, 2021 at 20:51
  • 1
    @AndrewHenle I am not allowed to use if statements, only the operators i provided Commented Apr 5, 2021 at 20:55
  • 1
    @ians Why operator restriction? What application needs that? Looks like that would obfuscate code. Commented Apr 5, 2021 at 21:47
  • 1
    Your code uses the assignment operator =, which is not on the approved list. (The point of this comment is that your restriction to use only those operators is silly.) Commented Apr 6, 2021 at 18:18

2 Answers 2

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

@chux-ReinstateMonica Thanks. Is it fixed now?
@chux-ReinstateMonica You're right. They are all actually boolean at that point.
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)) )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.