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;

{
// 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;

{
long sum = (long)a + (long)b;
if (sum <= SINT32_MIN) return SINT32_MIN;
if (sum >= SINT32_MAX) return SINT32_MAX;
return (int)sum;
}``````

Edited by batchprogram: n/a

3
Contributors
4
Replies
6
Views
7 Years
Discussion Span
Last Post by rubberman

Bitwise operations:

multiply by 2 == <<1
divide by 2 == >>1
subtract = -

So, if what I understand you to mean by "saturated" arithmetic, with limits of +-21474, then the problem becomes much more comprehensible. In any case, please clarify if I am making the appropriate assumptions. Your terminology is not what I have used in the past.

You'll also need to utilize modulus operations to determine if there are "left over bits".

You have control statement with comparison and casts in your code! Also modulus was not allowed!

Edited by pyTony: n/a

Missed that (no modulus operations)... Thanks! Naturally, modulus operations are basically "divide-by and test for remainder", and since divides are disallowed, that makes sense.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.