Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize integer and floating point multiplication

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

like image 898
Sirish Avatar asked Nov 30 '22 09:11

Sirish


1 Answers

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 );
like image 118
Lundin Avatar answered Dec 05 '22 06:12

Lundin