C# 翻译不同范围内成比例的数字

C# translate numbers proportional in different ranges

我正在尝试在两个数字范围之间按比例转换。 一侧有一个字节,在第二侧有不同范围的整数或浮点数,包括范围“0...X”和“-X...X”。

我该怎么做?有一些自动化的方法吗?我不需要很高的四舍五入精度,但我想避免为每个新范围制作新的 table ;-) 我找到了一个主题,但它是关于 Python 的,它需要重新定位每个不以零开头的范围:Translate numbers from a range to another range

示例 Int 模板:

namespace MyProgram
...
void Program()
{
byte[] foo;        // (0x00 ... 0xFF)
int bar;           // int or float
int rmin = -500;
int rmax = 500;
foo = /*input*/;
bar = Do_Translation (foo, rmin, rmax);
...}
private int Do_Translation (byte[] foo, int rmin, int rmax)
{
if (foo[0] > 0x80)
{
  //translate into range of 1...500
}
else if (foo[0] == 0x80)
{
  return 0;
}
  else if (foo[0] < 0x80)
{
  //translate into range of -500...-1
}
}

浮动模板示例:

namespace MyProgram
...
void Program()
{
byte[] foo;        // (0x00 ... 0xFF)
float bar;         // int or float
int rmin = 15.5;
int rmax = 100;
foo = /*input*/;
bar = Do_Translation (foo, rmin, rmax);
...}
private float Do_Translation (byte[] foo, int rmin, int rmax)
{
  //translate byte range of 0x00...0xFF into float range of 15.5...100
}

要将 byte[] 转换为 Int32 或浮点数,您可以使用 BitConverter class.

如我的评论所述,您需要计算出旧范围与新范围的比率。假设 rmin 和 rmax 是您的新范围最小值和新范围最大值,那么您还需要提供旧的最小值和最大值。类似于 this.