I am trying to optimize following operation where I have a large number of unsigned short inputs which needs to be scaled down by a certain factor. Is there a way to optimize it to not use floating point operations
unsigned short val = 65523U;
val = val * 0.943;
Note
I will be running above operation on a DSP where floating point operations are costly
The simplest way is to just use a 32 bit type that can hold the result:
uint16_t val = 65523U;
val = (uint_fast32_t)val * 943 / 1000;
Or if you want more type correctness and portability, while at the same time allowing the compiler to use the best possible integer type for the task:
#include <stdint.h>
uint_fast16_t val = UINT16_C(65523);
val = (uint_fast16_t) ( (uint_fast32_t)val * (uint_fast32_t)943 / (uint_fast32_t)1000 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With