C# ASCII码字符转换

C#单纯的字母数字ASCII码转换

字母转换成数字

byte[] array = new byte[1];   //定义一组数组array
array = System.Text.Encoding.ASCII.GetBytes(string); //string为待转换的字母
int asciicode = (short)(array[0]); //asciicode 为整数ASCII码
ASCII码 = Convert.ToString(asciicode); //将转换一的ASCII码转换成string型

数字转换成字母(1)

byte[] array = new byte[1];
array[0] = (byte)(Convert.ToInt32(ASCII码)); //ASCII码强制转换二进制
string str=Convert.ToString(System.Text.Encoding.ASCII.GetString(array));//str为ASCII码对应的字符

数字转换成字母(2)

System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] byteArray = new byte[] { (byte)ASCII码 };  
string str = asciiEncoding.GetString(byteArray);

实例:

string sVer  = "";
string strCheck = "10C";
string sLetter = strCheck.Substring(2, 1); // 获取strCheck第三位的字符

// 獲取sLetter資訊的Ascii碼
byte[] array = new byte[1];  //定义一组数组array
array = System.Text.Encoding.ASCII.GetBytes(sLetter); //string转换的字母
int nAsciicode = (short)(array[0]);

// 判斷是不是大寫字母
if (nAsciicode <= 65 || nAsciicode >= 90)
continue;

// 判斷sLetter字母前的所有大寫字母
for (int k = 65; k < nAsciicode; k++)
{
	// 將Ascii碼轉化為大寫字母
	System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
	byte[] byteArray = new byte[] { (byte)k };
	string strCharacter = asciiEncoding.GetString(byteArray);

	// 拼接版本.
	if (sVer == "")
	{
		if (strCheck.Length == 3)
		{
		  sVer = strCheck.Substring(0, 2) + strCharacter ;
		}
		else
		{
		  sVer = strCheck.Substring(0, 2) + strCharacter + strCheck.Substring(3, strCheck.Length - 3);
		}
	}
	else
	{
		if (strCheck.Length == 3)
		{
		  sVer += "," + strCheck.Substring(0, 2) + strCharacter;
		}
		else
		{
		  sVer += "," + strCheck.Substring(0, 2) + strCharacter + strCheck.Substring(3, strCheck.Length - 3);
	}
	}

}

上面实例运行结果应为:10A,10B

千里之行始于足下,原共勉之!

你可能感兴趣的:(c#,方法,c#,ascii码表)