CheckUtil.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. namespace GUI
  2. {
  3. public static class CheckUtil
  4. {
  5. public static void Func_sum_check(byte[] data, int offset, int len, byte[] check)
  6. {
  7. int i;
  8. ushort result = 0;
  9. for (i = 0; i < len; i++)
  10. {
  11. result += data[i + offset];
  12. }
  13. check[0] = (byte)result;
  14. check[1] = (byte)(result >> 8);
  15. }
  16. public static void Func_Xor_check(byte[] data, int offset, int len, out byte check)
  17. {
  18. int i;
  19. check = data[offset];
  20. for (i = 1; i < len; i++)
  21. {
  22. check ^= data[i + offset];
  23. }
  24. }
  25. public static bool ArrayEquals<T>(this T[] src, T[] other, int offset = 0)
  26. {
  27. for (int i = 0; i < src.Length; i++)
  28. if (!src[i].Equals(other[i + offset]))
  29. return false;
  30. return true;
  31. }
  32. public static T[] ArrayCombine<T>(this T[] src, T[] other)
  33. {
  34. T[] newT = new T[src.Length + other.Length];
  35. for (int i = 0; i < src.Length; i++) newT[i] = src[i];
  36. for (int i = 0; i < other.Length; i++) newT[i + src.Length] = other[i];
  37. return newT;
  38. }
  39. public static bool CheckData(this byte[] data)
  40. {
  41. byte[] check2 = new byte[2];
  42. Func_sum_check(data, 0, data.Length - 3, check2);
  43. if (!check2.ArrayEquals(data, data.Length - 3)) return false;
  44. Func_Xor_check(data, 0, data.Length - 1, out byte check);
  45. if (check != data[^1]) return false;
  46. return true;
  47. }
  48. public static byte[] PackData(this byte[] data)
  49. {
  50. byte[] check2 = new byte[2];
  51. Func_sum_check(data, 0, data.Length, check2);
  52. byte[] withSumCheck = data.ArrayCombine(check2);
  53. Func_Xor_check(withSumCheck, 0, withSumCheck.Length, out byte last);
  54. return withSumCheck.ArrayCombine(new byte[1] { last });
  55. }
  56. public static byte t(this bool b) => (byte)(b ? 1 : 0);
  57. }
  58. }