SerialInit.cs 2.0 KB

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