程序范例
本程序范例将建立四种不同的字节数据,并使用三种不同的编码方式将原本的字节数据转换为字符串,观察编码函式处理后所产生之结果,程序代码如下所示:
static void Main(string[] args)
{
byte[] ibyte1, ibyte2, ibyte4;
byte[] ibyte3 = new byte[1024];
ibyte1 = System.Text.Encoding.ASCII.GetBytes("0123456789");
ibyte2 = System.Text.Encoding.ASCII.GetBytes("章立民");
RandomNumberGenerator.Create().GetBytes(ibyte3);
ibyte4 = new byte[]{0,1,2,3,4};
Show(ibyte1);
Show(ibyte2);
Show(ibyte3);
Show(ibyte4);
Console.ReadLine();
}
private static void Show(byte[] Ibyte)
{
Console.WriteLine("/**********************************************/n");
Console.WriteLine("Ibyte[0]:" + Ibyte[0].ToString() + "n");
string ascii2str = Encoding.ASCII.GetString(Ibyte);
Console.WriteLine("ascii2str:" + ascii2str + "t");
Console.WriteLine("ascii2str.Length:" + ascii2str.Length + "n");
string unicode2str = Encoding.Unicode.GetString(Ibyte);
Console.WriteLine("unicode2str:" + unicode2str + "t");
Console.WriteLine("unicode2str.Length:" + unicode2str.Length + "n");
string utf82str = Encoding.UTF8.GetString(Ibyte);
Console.WriteLine("utf82str:" + utf82str + "t");
Console.WriteLine("utf82str.Length:" + utf82str.Length + "n");
byte[] ascii2byte = Encoding.ASCII.GetBytes(ascii2str);
byte[] unicode2byte = Encoding.Unicode.GetBytes(unicode2str);
byte[] utf82byte = Encoding.UTF8.GetBytes(utf82str);
Console.WriteLine(ascii2byte.Length + " " +
unicode2byte.Length + " " + utf82byte.Length + "n");
Console.WriteLine("/**********************************************/n");
}
执行完程序之后发现,ibyte1 变量以 ASCII 或是 UTF8 编码后,产生的字符串内容与长度皆与原来变量相同。ibyte2 变量以 ASCII 或是 UTF8 编码后,虽然产生的字符串数据长度与原来变量相同,但是数据内容与原来的变量不同。ibyte3 变量以ASCII编码后,产生的字符串数据长度与原来变量相同。 ibyte4 变量以 ASCII 或是 UTF8 编码后,产生的字符串数据长度与原来变量相同,但是数据内容与原来的变量不同。
从以上的结果可以得知,将字节转换为字符串之前,必须先针对数据内容,选择适合的转换函式,才能够得到符合需求的结果。
联系客服