字母转换成数字
byte[] array = new byte[1]; //定义一组数组array
array = System.Text.Encoding.ASCII.GetBytes(string); //string转换的字母
int asciicode = (short)(array[0]);
ASCII码 = Convert.ToString(asciicode); //将转换一的ASCII码转换成string型
数字转换成字母
byte[] array = new byte[1];
array[0] = (byte)(Convert.ToInt32(ASCII码)); //ASCII码强制转换二进制
转换后的字母= Convert.ToString(System.Text.Encoding.ASCII.GetString(array));
在编码的过程中很多时候会用到将某些数字的索引转化为字母,比方说Excel的单元格的列数在Excel中就用大写字母来表示,要把数字转换成字母可以使用C#的ASCIIEncoding类里的GetString方法。请参见以下示例:
///
/// 数字转字母
///
/// 要转换成字母的数字(数字范围在闭区间[65,90])
///
private string NunToChar(int number)
{
if (65 <= number && 90 >= number)
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] btNumber = new byte[] { (byte)number };
return asciiEncoding.GetString(btNumber);
}
return "数字不在转换范围内";
}
/// 数字转字母
///
/// 要转换成字母的数字(数字范围在闭区间[65,90])
///
private string NunToChar(int number)
{
if (65 <= number && 90 >= number)
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] btNumber = new byte[] { (byte)number };
return asciiEncoding.GetString(btNumber);
}
return "数字不在转换范围内";
}
///
/// 把1,2,3,...,35,36转换成A,B,C,...,Y,Z
///
/// 要转换成字母的数字(数字范围在闭区间[1,36])
///
private string NunberToChar(int number)
{
if (1 <= number && 36 >= number)
{
int num = number+64;
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] btNumber = new byte[] { (byte)num };
return asciiEncoding.GetString(btNumber);
}
return "数字不在转换范围内";
}
/// 把1,2,3,...,35,36转换成A,B,C,...,Y,Z
///
/// 要转换成字母的数字(数字范围在闭区间[1,36])
///
private string NunberToChar(int number)
{
if (1 <= number && 36 >= number)
{
int num = number+64;
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] btNumber = new byte[] { (byte)num };
return asciiEncoding.GetString(btNumber);
}
return "数字不在转换范围内";
}