Multi platform map function

Description

Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

Example
If you had an input range from 0 to 1023, and wanted an output from 0 to 255, based on the input, it would look like this.

map(val, 0, 1023, 0, 255)

If the input was 511 it would then return 127, because 511 is the half of 1023, and 127 the half of 255 (Rounded both down)

Arduino + C#

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
	return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

ASP

<%
function map(x, in_min, in_max, out_min, out_max)
	map = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
end function
%>

PHP

<?php
function map($x, $in_min, $in_max, $out_min, $out_max)
{
	$total= (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
	return $total;
}
?>

LSL

float map(integer x, integer in_min, integer in_max, integer out_min, integer out_max)
{
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

Leave a Reply