求c# 中文和字符串转成ascii码 和 ascii码转成字符。

最好能有实例

第1个回答  2013-03-29
在.NET中转化ASCII码,请您使用System.Text.ASCIIEncoding类。它提供了GetBytes()和GetChars()来实施转换。当然,您还可以在.NET联机手册中找到其他有用的函数。

下面是一个转换的例子:

////////////////////////////////////////////////////////////////////////////////////

using System;
using System.Text;

namespace ConsoleApplication3
{

class Class1
{

static void Main(string[] args)
{

// UTF-16字符串
string MyString = "Hello World ";

ASCIIEncoding AE1 = new ASCIIEncoding();

byte[] ByteArray1 = AE1.GetBytes(MyString);

//打印出ASCII码
for(int x = 0;x <= ByteArray1.Length - 1; x++)
{
Console.Write( "{0} ", ByteArray1[x]);
}

Console.Write( "\n ");

//把ASCII码转化为对应的字符

ASCIIEncoding AE2 = new ASCIIEncoding();
byte[] ByteArray2 = {72,101,108,108,111,32,87,111,114,108,100};
char[] CharArray = AE2.GetChars(ByteArray2);
for(int x = 0;x <= CharArray.Length - 1; x++)
{
Console.Write(CharArray[x]);
}

Console.Write( "\n ");

}
}
}
相似回答