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 over owing the way normal two's-complement addition
does, satu-
rating addition returns INT_MAX when there would be positive over
ow, and
INT_MIN when there would be negative over ow. Saturating arithmetic
is com-
monly used in programs that perform digital signal processing. Your
function
should follow the bit-level integer coding rules above.
#include <stdio.h> #include <limits.h> int saturating_add(int x, int y) { int w = sizeof(x) << 3; int addition = x + y; int mask = 1 << (w - 1); int msbFirstNumber = x & mask; int msbSecondNumber = y & mask; int msbAddition = addition & mask; int positiveOverflow = ~msbFirstNumber & ~msbSecondNumber & msbAddition; int negativeOverflow = msbFirstNumber & msbSecondNumber & !msbAddition; (positiveOverflow) && (addition = INT_MAX); (negativeOverflow) && (addition = INT_MIN); return addition; } int main() { int sum = saturating_add(5, 10); printf("The Sum Is : %d\n\n", sum); }
Get Answers For Free
Most questions answered within 1 hours.