I have a device driver that uses the following algorithm to convert a value received from a sensor (no bound range) to a different value (bound range).
The sensor’s values are usually within the 0-200 range but can exceed it, the maximum being about 4000 (this only happens when you use the sensor in an extreme way). I basically need a function that can do the following but without the giant if so it is more flexible.
It needs to take in the value, the step (in this case 20.0f) and the max output (in this case 10).
/* disregard the floating point numbers, I can cast them to int */
if (value <= 20.0f)
return 0;
else if (value <= 40.0f)
return 1;
else if (value <= 60.0f)
return 2;
else if (value <= 80.0f)
return 3;
else if (value <= 100.0f)
return 4;
else if (value <= 120.0f)
return 5;
else if (value <= 140.0f)
return 6;
else if (value <= 160.0f)
return 7;
else if (value <= 180.0f)
return 8;
else if (value <= 190.0f)
return 9;
else if (value >= 200.0f)
return 10;
return 0;
Edit: As @DSM noted, this has a fencepost error, and should be something like: