954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Signed saturated addition with only bitwise operations

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;
}
batchprogram
Newbie Poster
8 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
 

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.

rubberman
Posting Virtuoso
1,564 posts since Mar 2010
Reputation Points: 277
Solved Threads: 179
 

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

rubberman
Posting Virtuoso
1,564 posts since Mar 2010
Reputation Points: 277
Solved Threads: 179
 

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

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

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.

rubberman
Posting Virtuoso
1,564 posts since Mar 2010
Reputation Points: 277
Solved Threads: 179
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: