How do I map numbers in C# like with map in Arduino?

You can do it with an Extension Method (for decimal for example):

public static class ExtensionMethods
{
    public static decimal Map (this decimal value, decimal fromSource, decimal toSource, decimal fromTarget, decimal toTarget)
    {
        return (value - fromSource) / (toSource - fromSource) * (toTarget - fromTarget) + fromTarget;
    }
}

Then you can use it like:

decimal res = 2.Map(1, 3, 0, 10);
// res will be 5

private static int map(int value, int fromLow, int fromHigh, int toLow, int toHigh) 
{
    return (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
}

Tags:

C#

Arduino