Question

(15 marks) Write code for a function with the following prototype: /* Addition that saturates to...

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.

Homework Answers

Answer #1
#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);
}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions