I have a problem that seems trivial but proves not to be...
In a C program intended for the Blackfin processor, I want to add up two short signed integers a and b and coerce the result to the range of short int.
- if a+b > 2^15-1 then set a+b=2^15-1
- if a+b < -2^15 then set a+b=-2^15.
Of course, this can be done by
- using an intermediate variable with longer data type (e.g., signed int) to store the sum (a+b);
- checking the above conditions;
- setting the min/max value when applicable.
However, I am looking for something more efficient, ideally without intermediate variables and possibly without "if - then" operations.
In assembler, I would for instance do this by checking the carry output of the adder (is there one?).
Any suggestions how to do this in C? Maybe by checking for sign changes?
Thank you for your help!