I'm doing some homework for a computer systems class and all is well except this one problem that I can't seem to find a solution to due to the limitations.

The problem requires me to write a function that performs addition on 32-bit signed integers but saturates the result to -21474... when there would be underflow, and 21474... when there would be overflow. The limitations are it can only be written with bitwise operations, addition, and subtraction(meaning no control statements, functions, macros, division, multiplication, modulus, comparisons, casting, and no resources from libraries).

I have attempted to write this several times but to no avail, however I have figured out how to get some information.

```
const int SINT32_MIN = 0x80000000;
const int SINT32_MAX = 0x7FFFFFFF;
int SaturatingAdd(int a, int b)
{
// Determine if the signs are different. Under/Overflow is impossible if the signs differ.
bool sdiff = ((a & 0x80000000) ^ (b & 0x80000000));
return something;
}
```

This is a solution I came up with using some of the limitations.

```
const int SINT32_MIN = 0x80000000;
const int SINT32_MAX = 0x7FFFFFFF;
int SaturatingAdd(int a, int b)
{
long sum = (long)a + (long)b;
if (sum <= SINT32_MIN) return SINT32_MIN;
if (sum >= SINT32_MAX) return SINT32_MAX;
return (int)sum;
}
```

*Edited 5 Years Ago by batchprogram*: n/a