SerialInit.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using SXLibrary;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace MOKA_Factory_Tools
  7. {
  8. class SerialInit
  9. {
  10. public static string ByteToHex(byte[] comByte)
  11. {
  12. StringBuilder builder = new StringBuilder(comByte.Length * 3);
  13. foreach (byte data in comByte)
  14. {
  15. builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
  16. }
  17. return builder.ToString().ToUpper();
  18. }
  19. public static byte[] HexToByte(string msg)
  20. {
  21. try
  22. {
  23. msg = msg.Replace(" ", "");//移除空格
  24. //create a byte array the length of the
  25. //divided by 2 (Hex is 2 characters in length)
  26. byte[] comBuffer = new byte[msg.Length / 2];
  27. for (int i = 0; i < msg.Length; i += 2)
  28. {
  29. //convert each set of 2 characters to a byte and add to the array
  30. comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
  31. }
  32. return comBuffer;
  33. }
  34. catch(Exception e)
  35. {
  36. Log.WriteErrorLog(string.Format("HexToByte Error: {0} -> {1}", msg, e.Message));
  37. }
  38. return new byte[] { };
  39. }
  40. public static bool BytesCompare_Base64(byte[] b1, byte[] b2)
  41. {
  42. if (b1 == null || b2 == null) return false;
  43. if (b1.Length != b2.Length) return false;
  44. return string.Compare(Convert.ToBase64String(b1), Convert.ToBase64String(b2), false) == 0 ? true : false;
  45. }
  46. /// <summary>
  47. /// 将16进制字符串转成字节;
  48. /// </summary>
  49. /// <param name="hexString"></param>
  50. /// <returns></returns>
  51. public static byte[] strToToHexByte(string hexString)
  52. {
  53. hexString = hexString.Replace(" ", "");
  54. if ((hexString.Length % 2) != 0)
  55. hexString += " ";
  56. byte[] returnBytes = new byte[hexString.Length / 2];
  57. for (int i = 0; i < returnBytes.Length; i++)
  58. returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
  59. return returnBytes;
  60. }
  61. }
  62. }