</>EmbeddedInterview
← All problems · Signal Processing

Saturating 16-bit Sensor Addition

Easy

Add two signed 16-bit samples and clamp to the representable range. Implement int16_t sat_add(int16_t a, int16_t b).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Widen before adding.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>

int16_t sat_add(int16_t a, int16_t b)
{
    int32_t s=(int32_t)a+b; if(s>INT16_MAX)return INT16_MAX; if(s<INT16_MIN)return INT16_MIN; return (int16_t)s;
}

A wider intermediate avoids overflow before clamping.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    
    CHECK(sat_add(30000,10000)==32767);
    CHECK(sat_add(-30000,-10000)==-32768);
    CHECK(sat_add(12,-5)==7);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}