using System.Text;
using System;
namespace Ropin.Environmentally.LoRaService
{
public class StringHelper
{
///
/// 将字符串转换为16进制字符串
///
///
///
///
public static string StringToHexString(string s, Encoding encode)
{
byte[] b = encode.GetBytes(s);//按照指定编码将string编程字节数组
string result = string.Empty;
for (int i = 0; i < b.Length; i++)//逐字节变为16进制字符,以%隔开
{
result += " " + Convert.ToString(b[i], 16);
}
return result.Substring(1, result.Length - 1);
}
///
/// 将16进制字符串,转换为字符串
///
///
///
///
public static string HexStringToString(string hs, Encoding encode)
{
//以 分割字符串,并去掉空字符
string[] chars = hs.Split(' ');
byte[] b = new byte[chars.Length];
//逐个字符变为16进制字节数据
for (int i = 0; i < chars.Length; i++)
{
b[i] = Convert.ToByte(chars[i], 16);
}
//按照指定编码将字节数组变为字符串
return encode.GetString(b);
}
///
/// 字符串转16进制字节数组
///
///
///
public static byte[] StringToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
///
/// 字节数组转16进制字符串
///
///
///
public static string ByteToHexString(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += " " + bytes[i].ToString("X2");
}
}
return returnStr.Substring(1, returnStr.Length - 1);
}
}
}