C#字符串和16进制转换

时间:2023-03-09 16:01:25
C#字符串和16进制转换

public static string StrToHex(string mStr) //返回处理后的十六进制字符串
{
return BitConverter.ToString(
ASCIIEncoding.Default.GetBytes(mStr)).Replace("-", " ");
} /* StrToHex */

public static string HexToStr(string mHex) // 返回十六进制代表的字符串
{
mHex = mHex.Replace(" ", "");
if (mHex.Length <= 0) return "";
byte[] vBytes = new byte[mHex.Length / 2];
for (int i = 0; i < mHex.Length; i += 2)
if (!byte.TryParse(mHex.Substring(i, 2), NumberStyles.HexNumber, null, out vBytes[i / 2]))
vBytes[i / 2] = 0;
return ASCIIEncoding.Default.GetString(vBytes);
}