CHex2String.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Dispatch
  6. {
  7. internal class CHex2String
  8. {
  9. internal static byte[] HexString2Byte(string msg)
  10. {
  11. msg = msg.Replace(" ", "");//移除空格
  12. //create a byte array the length of the
  13. //divided by 2 (Hex is 2 characters in length)
  14. byte[] comBuffer = new byte[msg.Length / 2];
  15. for (int i = 0; i < msg.Length; i += 2)
  16. {
  17. //convert each set of 2 characters to a byte and add to the array
  18. comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
  19. }
  20. return comBuffer;
  21. }
  22. internal static int[] StringArrayToIntArray(string[] msg)
  23. {
  24. int[] comBuffer = new int[msg.Length];
  25. for (int i = 0; i < msg.Length; i ++)
  26. {
  27. comBuffer[i] = Convert.ToInt32(msg[i]);
  28. }
  29. return comBuffer;
  30. }
  31. internal static string Byte2HexString(byte[] comByte, int len)
  32. {
  33. StringBuilder builder = new StringBuilder(len * 3);
  34. /*foreach (byte data in comByte)
  35. {
  36. builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
  37. }*/
  38. for (int i = 0; i < len; i++)
  39. {
  40. builder.Append(Convert.ToString(comByte[i], 16).PadLeft(2, '0').PadRight(3, ' '));
  41. }
  42. return builder.ToString().ToUpper();
  43. }
  44. }
  45. }