2.73 Saturating Add

★★

Problem:

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$ in programs that perform digital signal processing.

Code:

#include <stdio.h>
#include <assert.h>
#include <limits.h>

int saturating_add(int x, int y) {
    int sum = x + y;
    int mask = INT_MIN;
    int pos_flag = !(x & mask) && !(y & mask) && (sum & mask);
    int neg_flag = (x & mask) && (y & mask) && !(sum & mask);
    (pos_flag && (sum = INT_MAX) || neg_flag && (sum = INT_MIN));
    return sum;
}

int main() {
    assert(saturating_add(0x80000000, 0x80000000)==INT_MIN);
    assert(saturating_add(0x10, 0x20)==0x30);
    assert(saturating_add(0x7FFFFFFF, 0x7FFFFFFF)==INT_MAX);
    return;
}

Last updated