StringHelper.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Text;
  2. using System;
  3. namespace Ropin.Environmentally.LoRaService
  4. {
  5. public class StringHelper
  6. {
  7. /// <summary>
  8. /// 将字符串转换为16进制字符串
  9. /// </summary>
  10. /// <param name="s"></param>
  11. /// <param name="encode"></param>
  12. /// <returns></returns>
  13. public static string StringToHexString(string s, Encoding encode)
  14. {
  15. byte[] b = encode.GetBytes(s);//按照指定编码将string编程字节数组
  16. string result = string.Empty;
  17. for (int i = 0; i < b.Length; i++)//逐字节变为16进制字符,以%隔开
  18. {
  19. result += " " + Convert.ToString(b[i], 16);
  20. }
  21. return result.Substring(1, result.Length - 1);
  22. }
  23. /// <summary>
  24. /// 将16进制字符串,转换为字符串
  25. /// </summary>
  26. /// <param name="hs"></param>
  27. /// <param name="encode"></param>
  28. /// <returns></returns>
  29. public static string HexStringToString(string hs, Encoding encode)
  30. {
  31. //以 分割字符串,并去掉空字符
  32. string[] chars = hs.Split(' ');
  33. byte[] b = new byte[chars.Length];
  34. //逐个字符变为16进制字节数据
  35. for (int i = 0; i < chars.Length; i++)
  36. {
  37. b[i] = Convert.ToByte(chars[i], 16);
  38. }
  39. //按照指定编码将字节数组变为字符串
  40. return encode.GetString(b);
  41. }
  42. /// <summary>
  43. /// 字符串转16进制字节数组
  44. /// </summary>
  45. /// <param name="hexString"></param>
  46. /// <returns></returns>
  47. public static byte[] StringToHexByte(string hexString)
  48. {
  49. hexString = hexString.Replace(" ", "");
  50. if ((hexString.Length % 2) != 0)
  51. hexString += " ";
  52. byte[] returnBytes = new byte[hexString.Length / 2];
  53. for (int i = 0; i < returnBytes.Length; i++)
  54. returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
  55. return returnBytes;
  56. }
  57. /// <summary>
  58. /// 字节数组转16进制字符串
  59. /// </summary>
  60. /// <param name="bytes"></param>
  61. /// <returns></returns>
  62. public static string ByteToHexString(byte[] bytes)
  63. {
  64. string returnStr = "";
  65. if (bytes != null)
  66. {
  67. for (int i = 0; i < bytes.Length; i++)
  68. {
  69. returnStr += " " + bytes[i].ToString("X2");
  70. }
  71. }
  72. return returnStr.Substring(1, returnStr.Length - 1);
  73. }
  74. }
  75. }