MessageVerify.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. namespace Vinno.FIS.Sonopost.Features.Oled
  2. {
  3. public static class MessageVerify
  4. {
  5. /// <summary>
  6. /// 偶校验算法获得校验码
  7. /// </summary>
  8. /// <param name="date"></param>
  9. /// <returns></returns>
  10. public static byte[] EvenCode(byte[] data)
  11. {
  12. byte[] bVerify = new byte[data.Length / 8 + 2];//校验位接收数组
  13. bVerify[bVerify.Length - 1] = (byte)bVerify.Length;//校验位长度
  14. //计算校验位数据
  15. for (int i = 0; i < data.Length; i++)//每个位去处理
  16. {
  17. if (GetOddEvenVerify(data[i]))
  18. {//奇数 //1;
  19. set_bit(ref bVerify[i / 8], i);
  20. }
  21. else
  22. {//偶数//0;
  23. clr_bit(ref bVerify[i / 8], i);
  24. }
  25. }
  26. return bVerify;
  27. }
  28. /// <summary>
  29. /// 判断当前位1的个数是奇数个还是偶数个
  30. /// </summary>
  31. /// <param name="bData"></param>
  32. /// <returns>True 为奇数个 False 为偶数个</returns>
  33. private static bool GetOddEvenVerify(byte bData)
  34. {
  35. byte bcCount = 0; /* 字节内1的个数 */
  36. for (int i = 0; i < 8; i++)
  37. {
  38. if ((bData & (byte)0x01) == 1)
  39. {
  40. bcCount++;
  41. }
  42. bData >>= 1;
  43. }
  44. return ((bcCount & (byte)0x01) == 1);
  45. }
  46. /// <summary>
  47. /// 置位x的y位
  48. /// </summary>
  49. /// <param name="x"></param>
  50. /// <param name="y"></param>
  51. private static void set_bit(ref byte x, int y)
  52. {
  53. x = (byte)(x | (0x01 << (y)));
  54. }
  55. /// <summary>
  56. /// 清零x的y位
  57. /// </summary>
  58. /// <param name="x"></param>
  59. /// <param name="y"></param>
  60. private static void clr_bit(ref byte x, int y)
  61. {
  62. x = (byte)(x & ~(0x01 << (y)));
  63. }
  64. public static void Check(byte[] data, ref byte result, int len)
  65. {
  66. byte noBit = 0, num = 0, tem_re = 0, tem_s = 0;
  67. int index = 0;
  68. while (len-- > 0)
  69. {
  70. tem_s = data[index];
  71. while (tem_s > 0)
  72. {
  73. tem_s = (byte)(tem_s & (tem_s - 1));
  74. num++;
  75. }
  76. if ((num & 0x01) > 0)
  77. {
  78. set_bit(ref tem_re, noBit);
  79. }
  80. noBit++;
  81. if (noBit > 7)
  82. {
  83. noBit = 0;
  84. result++;
  85. result = tem_re;
  86. tem_re = 0;
  87. }
  88. index++;
  89. num = 0;
  90. }
  91. }
  92. }
  93. }