C# ASCII码字符转换

9 篇文章 1 订阅

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

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

  • 2
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值