#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 ";
}
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;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.