Skip to content

Instantly share code, notes, and snippets.

@gue-ni
Last active October 20, 2023 11:05
Show Gist options
  • Save gue-ni/96065ad3f015cbe9c69f096b94478078 to your computer and use it in GitHub Desktop.
Save gue-ni/96065ad3f015cbe9c69f096b94478078 to your computer and use it in GitHub Desktop.
Map numbers from one range to another
#include <tuple>
#include <cassert>
template<typename T>
T map_range(T s, const std::pair<T,T>& in, const std::pair<T,T>& out)
{
auto [in_min, in_max] = in;
auto [out_min, out_max] = out;
assert(in_min <= s && s <= in_max);
return out_min + (s - in_min) * (out_max - out_min) / (in_max - in_min);
}
template<typename T>
T map_range(T s, T in_min, T in_max, T out_min, T out_max)
{
assert(in_min <= s && s <= in_max);
return out_min + (s - in_min) * (out_max - out_min) / (in_max - in_min);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment