HRInt.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using Island.StandardLib.Storage;
  2. using System;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. namespace Island.StandardLib.Math
  6. {
  7. /// <summary>
  8. /// 表示一个小数点后一位的0-998的小数,它将可以转换为通用的两字节Char
  9. /// </summary>
  10. public struct HRInt : IStorable
  11. {
  12. char hrValue;
  13. /// <summary>
  14. /// 使用数据交换应用的两字节Char初始化
  15. /// </summary>
  16. /// <param name="HR"></param>
  17. public HRInt(char HR)
  18. {
  19. hrValue = HR;
  20. }
  21. /// <summary>
  22. /// 使用浮点数初始化
  23. /// </summary>
  24. /// <param name="source"></param>
  25. public HRInt(float source, bool requestStrictMode = true)
  26. {
  27. int i = (int)(source * 10);
  28. if (i > 9998 || i < 0)
  29. {
  30. if (requestStrictMode)
  31. throw new Exception("Island.Server.Math.HRInt: 无效的转换: " + source);
  32. else
  33. {
  34. if (i < 0) i = 0;
  35. if (i > 9998) i = 9998;
  36. }
  37. }
  38. i++;
  39. string ci = i.ToString();
  40. if (i < 1000)
  41. {
  42. ci = "0" + ci;
  43. if (i < 100)
  44. {
  45. ci = "0" + ci;
  46. if (i < 10)
  47. ci = "0" + ci;
  48. }
  49. }
  50. hrValue = UnicodeToString(ci)[0];
  51. }
  52. /// <summary>
  53. /// 获取浮点数表示
  54. /// </summary>
  55. public float Value
  56. {
  57. get
  58. {
  59. return (int.Parse(StringToUnicode(hrValue + "")) - 1) / 10f;
  60. }
  61. }
  62. /// <summary>
  63. /// 获取数据交换应用的两字节Char表示
  64. /// </summary>
  65. public char HRValue
  66. {
  67. get
  68. {
  69. return hrValue;
  70. }
  71. }
  72. static string StringToUnicode(string source)
  73. {
  74. byte[] bytes = Encoding.Unicode.GetBytes(source);
  75. StringBuilder stringBuilder = new StringBuilder();
  76. for (int i = 0; i < bytes.Length; i += 2)
  77. stringBuilder.AppendFormat("{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
  78. return stringBuilder.ToString();
  79. }
  80. static string UnicodeToString(string source)
  81. {
  82. return new Regex(@"([0-9A-F]{4})", RegexOptions.IgnoreCase).Replace(
  83. source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
  84. }
  85. public void ReadFromData(DataStorage data)
  86. {
  87. data.Read(out hrValue);
  88. }
  89. public void WriteToData(DataStorage data)
  90. {
  91. data.Write(hrValue);
  92. }
  93. }
  94. }