Possible Duplicate:
Convert a number range to another range, maintaining ratio
So I have a function that returns values within 0 and 255 and I need to convert these values to something between -255 and 255 So 200 would be roughly 145, 150 would be roughly 45 and so on.. I have looked at Convert a number range to another range, maintaining ratio but the formulas there won't work. Any other formula I could use?
public static int ConvertRange(
int originalStart, int originalEnd, // original range
int newStart, int newEnd, // desired range
int value) // value to convert
{
double scale = (double)(newEnd - newStart) / (originalEnd - originalStart);
return (int)(newStart + ((value - originalStart) * scale));
}
Try this:
int Adjust( int num )
{
return num * 2 - 255;
}
General solution for arbitrary range...
var val1 = 200;
var min1 = 0;
var max1 = 255;
var range1 = max1 - min1;
var min2 = -255;
var max2 = 255;
var range2 = max2 - min2;
var val2 = val1*range2/range1 + min2;
public int ConvertRange(
int originalStart, int originalEnd,
int newStart, int newEnd,
int value)
{
int originalDiff = originalEnd - originalStart;
int newDiff = newEnd - newStart;
int ratio = newDiff / originalDiff;
int newProduct = value * ratio;
int finalValue = newProduct + newStart;
return finalValue;
}
Adjusted = original / 255 * 510 - 255
145 = 200 / 255 * 510 - 255
45 = 145 / 255 * 510 - 255
精彩评论