Simvik

Saturating addition

Add two 16-bit samples and clamp instead of wrapping. An easy embedded C problem (Fixed-point and signal processing), run and graded in the browser.

easy · Fixed-point and signal processing · saturation

When two audio samples are mixed, a sum that wraps around turns a loud passage into a loud click. Saturating keeps it at the limit instead.

Return a + b, clamped to the range of int16_t (-32768 to 32767).

Starter code

int16_t sat_add16(int16_t a, int16_t b) {
  // Wraps on overflow: 30000 + 10000 becomes -25536.
  return (int16_t)(a + b);
}

Example tests

In range

printf("%d\n", sat_add16(100, 200));

Expected output:

300

Positive saturation

printf("%d\n", sat_add16(30000, 10000));

Expected output:

32767

Learn it first

More Fixed-point and signal processing problems