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;
}

Recommended Answers

All 4 Replies

Bitwise operations:

multiply by 2 == <<1
divide by 2 == >>1
add == +
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!

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.