Alex Alex - 3 months ago 9
C Question

Matlab int16() C equivalent?

In Matlab there is a function called int16, that rounds e.g. double values to the next integer. Is there any simple equivalent in C to that?

Especially for the rounding of negative numbers, e.g. -1.65 to -2 and 1.33 to -1.

Answer

The int16 function, rounds and clamps the values. So an equivalent would look like this

int16_t  int16( double d ) 
{
  return isnan(d) ? 0 : (d > 32767.0) ? 
    32767 : 
    (d <-32768.0) ? -32768 : (int16_t)round(d)) ;
}

EDIT: int16 also returns 0 for NAN input, so handle this as well.

Also note, that the code really needs the case differentiations, as the conversion of double to int16_t in C is undefined for NAN and values outside of the range of the target integer.