Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

#include <stdint.h> #include <iostream> #include <cassert> #include <climits> #i

ID: 3871436 • Letter: #

Question

#include <stdint.h>
#include <iostream>
#include <cassert>
#include <climits>

#include "q5.h"

int saturating_add(int x, int y);

{

//Solution needed here.

}


////////////////////////////////////////////////////////////////
// test code
void test_sat_1_plus_1()
{
    assert(saturating_add(1,1) == 2);
}
void test_neg_ov()
{
    assert(saturating_add(INT_MIN, -5) == INT_MIN);
    assert(saturating_add(INT_MIN, INT_MIN) == INT_MIN);
}
void test_pos_ov()
{
    assert(saturating_add(INT_MAX, 1) == INT_MAX);
}
void test_big_pos_ov()
{
    assert(saturating_add(INT_MAX, INT_MAX) == INT_MAX);
}
int main()
{
    std::cout << "for this machine, sizeof(int)=" << sizeof(int) << std::endl;
    test_sat_1_plus_1();
    test_neg_ov();
    test_pos_ov();
    test_big_pos_ov();
    std::cout << "Ok ";
}

5. (5 marks) 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 twos-complement addition does, satu- rating addition returns INT_MAX when there would be positive overflow, and INT_MIN when there would be negative overflow. Saturating arithmetic is com- monly used in programs that perform digital signal processing. Your function should follow the bit-level integer coding rules above.

Explanation / Answer

int saturating_add(int x, int y);

{

uint32_t a = (uint32_t) x;

uint32_t b = (uint32_t) y;

uint32_t c;

c = (a > 0xFFFFFFFF -b) ? 0xFFFFFFFF : a+b;

return (int) c;

}