Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed point multiplication

Tags:

c

fixed-point

I need to convert a value from one unit to another according to a non constant factor. The input value range from 0 to 1073676289 and the range value range from 0 to 1155625. The conversion can be described like this:

output = input * (range / 1073676289)

My own initial fixed point implementation feels a bit clumsy:

// Input values (examples)
unsigned int input = 536838144;  // min 0, max 1073676289
unsigned int range = 1155625;    // min 0, max 1155625

// Conversion
unsigned int tmp = (input >> 16) * ((range) >> 3u);
unsigned int output = (tmp / ((1073676289) >> 16u)) << 3u;

Can my code be improved to be simpler or to have better accuracy?


1 Answers

This will give you the best precision with no floating point values and the result will be rounded to the nearest integer value:

output = (input * (long long) range + 536838144) / 1073676289;
like image 64
user1871166 Avatar answered Jan 25 '26 19:01

user1871166