转换方法一:
//单个ASCII码值转成string字符:
public static string AsciiToString(int asciiCode)
{
if (asciiCode >= 0 && asciiCode <= 255)
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] byteArray = new byte[] { (byte)asciiCode };
string strCharacter = asciiEncoding.GetString(byteArray);
return (strCharacter);
}
else
{
throw new Exception("ASCII Code is not valid.");
}
}
//字符转ASCII码:
public static int StringToAsc(string character)
{
if (character.Length == 1)
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
return (intAsciiCode);
}
else
{
throw new Exception("Character is not valid.");
}
}
转换方法二:
/// <summary>
/// 此方法用于将普通字符串转换成16进制的字符串。
/// </summary>
/// <param name="_str">要转换的字符串。</param>
/// <returns></returns>
public string StringToGBKString(string _str)
{
string dt = "";
byte[] byStr = Encoding.GetEncoding("GB2312").GetBytes(_str);
foreach (var item in byStr)
{
dt += item.ToString("X2");
}
return dt;
}
private string GetStringFromAsciiHex(string input)
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
string acc = "";
if (input.Length % 2 == 0)
{
byte[] bytes = new byte[input.Length / 2];
for (int i = 0; i < input.Length; i += 2)
{
string hex = input.Substring(i, 2);
bytes[i/2] = Convert.ToByte(hex, 16);
}
acc = asciiEncoding.GetString(bytes);
}
return acc;
}