Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 'map' number ranges

Tags:

c++

c

Is there a better way in C or C++, or just mathematically in general, to map ratios of numbers while preserving or rounding data?

Take the following example

double cdp = 17000.0;    
float integ = 30000.0 / 255;
int val = cdp / integ;

color = color + RGB(val, val, val);

Here I want to map a range of numbers [0, 30000] to a value [0, 255]

like image 340
grep Avatar asked Sep 06 '25 03:09

grep


1 Answers

You can use a simple linear interpolation to do it, if I'm understanding correctly. It would work like this:

x = (inValue - minInRange) / (maxInRange - minInRange);
result = minOutRange + (maxOutRange - minOutRange) * x

where inValue is the number out of 30,000 in your example. minInRange = 0, maxInRange = 30,000, minOutRange = 0, maxOutRange = 255.

like image 130
user1118321 Avatar answered Sep 07 '25 20:09

user1118321