主题:  C# 中得到ASCII码的代码怎么写

蓝鲸

职务:版主
等级:5
金币:42.1
发贴:2614
注册:2001/12/20 15:57:57
#12004/10/7 1:58:57
VB.NET中有Asc()函数,可是在C#中没有。用(int)chr不行,用ASCIIEncoding的GetBytes只能得到有限的字符ASCII码,Encoding.Unicode的GetBytes也不能给出中文的码,只有UTF8能给出,但与Asc()给出的不同。不知谁试过C#中的ASCII码?


非常大鱼

缺缺

职务:管理员
等级:8
金币:41.0
发贴:9620
注册:2004/1/14 19:14:47
#22004/10/12 21:40:27
using System; 
class ASCII { 
	static void Main(){ 
		Console.WriteLine("Please input a char:"); 
		try{
			string str = Console.ReadLine();
			char chr = Convert.ToChar(str);
			Console.WriteLine("{0}\t->\t{1}",str,Convert.ToInt32(chr).ToString());
		}catch(Exception ex){
			Console.WriteLine("Error:\t"+ ex.Message);
		}
	} 
}



蓝鲸

职务:版主
等级:5
金币:42.1
发贴:2614
注册:2001/12/20 15:57:57
#32004/10/12 23:29:54
斑竹,谢谢,不过好象有点问题
我测试一下,单字节字符好象可以,但双字节的中文就与VB的ASC有差别了。
如“我”字,VB的ASC值为-12590,而Convert.ToInt32值为25105。

我自己编了个函数,写在类中

/// <summary>
/// 得到字符的ASCII码
/// </summary>
public static int ASCII(char chr)
{
    Encoding ecode = Encoding.GetEncoding("GB18030");
    Byte[] codeBytes = ecode.GetBytes(chr.ToString());
    if ( IsTwoBytesChar(chr) )
    {
        // 双字节码为高位乘256,再加低位
        // 该为无符号码,再减65536
        return (int)codeBytes[0] * 256 + (int)codeBytes[1] - 65536;
    }
    else
    {
        return (int)codeBytes[0];
    }
}

/// <summary>
/// 是否为双字节字符。
/// </summary>
public static bool IsTwoBytesChar(char chr)
{
    string str =chr.ToString();
    // 使用中文支持编码
    Encoding ecode = Encoding.GetEncoding("GB18030");
    if (ecode.GetByteCount(str) == 2)
    {
        return true;
    }
    else
    {
        return false;
    }
}

好麻烦,不过得出结果与VB是一样的。只知道支持中英文,但其它的不知道了。


非常大鱼