18.2k views
4 votes
Write code for a function with the following prototype: /* Addition that saturates to TMin or TMax */ int saturating_add(int x, int y); Instead of overflowing the way normal two's-complement addition does, saturating addition returns TMax when there would be positive overflow, and TMin when there would be negative overflow. Saturating arithmetic is commonly used in programs that perform digital signal processing. Your function should follow the bit-level integer coding rules (page 128).

1 Answer

3 votes

Answer:

See explaination

Step-by-step explanation:

program code.

/* PRE PROCESSOR DIRECTIVES */

#include<stdio.h>

/* PRE-DEFINED VALUES FOR TMAX AND TMIN */

#define TMax 2147483647

#define TMin (-TMax -1)

/* saturating_add(int,int) METHOD IS CALLED HERE */

int saturating_add(int firstNumber, int secondNumber)

{

/*

FOR BETTER UNDERSTANDING, LETS TAKE TEST CASE,

WHERE firstNumber = 5 AND secondNumber = 10

*/

int w = sizeof(firstNumber) << 3;

/*

sizeof(firstNumber) VALUE IS 4, SO USING BINARY LEFT SHIFT OPERATOR TO THREE PLACES,

WE HAVE NOW VALUE 32, ASSIGNED TO w

*/

/* ADDITION IS CALCULATED => 15 */

int addition = firstNumber + secondNumber;

/*

MASK INTEGER VARIABLE IS TAKEN

mask BIT IS LEFT SHIFTED TO 31 PLACES => 2^31 IS THE NEW VALUE

*/

int mask = 1 << (w - 1);

/* FIRST NUMBER MOST SIGNIFICANT BIT IS CALCULATED BY USING AND OPERATOR */

int msbFirstNumber = firstNumber & mask;

/* SECOND NUMBER MOST SIGNIFICANT BIT IS CALCULATED BY USING AND OPERATOR */

int msbSecondNumber = secondNumber & mask;

/* MOST SIGNIFICANT BIT OF ADDITION IS CALCULATED BY USING AND OPERATOR */

int msbAddition = addition & mask;

/* POSITIVE OVERFLOW IS DETERMINED */

int positiveOverflow = ~msbFirstNumber & ~msbSecondNumber & msbAddition;

/* NEGATIVE OVERFLOW IS DETERMINED */

int negativeOverflow = msbFirstNumber & msbSecondNumber & !msbAddition;

/* THE CORRESPONDING VALUE IS RETURNED AS PER THE SATURATING ADDITION RULES */

(positiveOverflow) && (addition = TMax);

(negativeOverflow) && (addition = TMin);

return addition;

}

/* MAIN FUNCTION STARTS HERE */

int main(){

/* TEST CASE */

int sum = saturating_add(5, 10);

/* DISPLAY THE RESULT OF TEST CASE */

printf("The Sum Is : %d\\\\",sum);

}

User BluesRockAddict
by
5.0k points