Converter.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6. namespace Aitex.Core.Util
  7. {
  8. public static class Converter
  9. {
  10. ///// <summary>
  11. ///// Unit converter from physical to logical in linear formula
  12. ///// </summary>
  13. ///// <returns></returns>
  14. public static double Phy2Logic(double physicalValue, double logicalMin, double logicalMax, double physicalMin, double physicalMax)
  15. {
  16. var ret = (logicalMax - logicalMin) * (physicalValue - physicalMin) / (physicalMax - physicalMin) + logicalMin;
  17. //if (ret < logicalMin) ret = logicalMin;
  18. //if (ret > logicalMax) ret = logicalMax;
  19. if (double.IsNaN(ret)) throw new DivideByZeroException("Phy2Logic除0操作");
  20. return ret;
  21. }
  22. ///// <summary>
  23. ///// Unit converter from logical to physical in linear formula
  24. ///// </summary>
  25. ///// <returns></returns>
  26. public static double Logic2Phy(double logicalValue, double logicalMin, double logicalMax, double physicalMin, double physicalMax)
  27. {
  28. var ret = (physicalMax - physicalMin) * (logicalValue - logicalMin) / (logicalMax - logicalMin) + physicalMin;
  29. if (ret < physicalMin) ret = physicalMin;
  30. if (ret > physicalMax) ret = physicalMax;
  31. if (double.IsNaN(ret))
  32. throw new DivideByZeroException("Logic2Phy除0操作");
  33. return ret;
  34. }
  35. /// <summary>
  36. /// 只按占用的字节转换,不检查范围
  37. /// </summary>
  38. /// <param name="high"></param>
  39. /// <param name="low"></param>
  40. /// <returns></returns>
  41. public static float TwoUInt16ToFloat(UInt16 high, UInt16 low)
  42. {
  43. Int32 sum = (high << 16) + (low & 0xFFFF);
  44. byte[] bs = BitConverter.GetBytes(sum);
  45. return BitConverter.ToSingle(bs, 0);
  46. }
  47. public static int TwoInt16ToInt32(Int16 high, Int16 low)
  48. {
  49. UInt32 tmp = (ushort)low + (UInt32)(((ushort)high) << 16);
  50. return tmp > Int32.MaxValue ? (int)((~tmp + 1) * -1) : (int)tmp;////unsigned to signed
  51. }
  52. public static float TwoInt16ToFloat(Int16 high, Int16 low)
  53. {
  54. Int32 sum = (high << 16) + (low & 0xFFFF);
  55. byte[] bs = BitConverter.GetBytes(sum);
  56. return BitConverter.ToSingle(bs, 0);
  57. }
  58. }
  59. }