将Byte数组转化为String

** 问题 ** ** **

FCL 得很多方法的返回值都是包含字符的 Byte 数组而不是返回一个 String ,这样的方法包含在如下的类中:

· System.Net.Sockets.Socket.Receive

· System.Net.Sockets.Socket.ReceiveFrom

· System.Net.Sockets.Socket.BeginReceive

· System.Net.Sockets.Socket.BeginReceiveFrom

· System.Net.Sockets.NetworkStream.Read

· System.Net.Sockets.NetworkStream.BeginRead

· System.IO.BinaryReader.Read

· System.IO.BinaryReader.ReadBytes

· System.IO.FileStream.Read

· System.IO.FileStream.BeginRead

· System.IO.MemoryStream // Constructor

· System.IO.MemoryStream.Read

· System.IO.MemoryStream.BeginRead

· System.Security.Cryptography.CryptoStream.Read

· System.Security.Cryptography.CryptoStream.BeginRead

· System.Diagnostics.EventLogEntry.Data

由这些方法返回的 Byte 数组中包含的通常是以 ASCII 编码或是 Unicode 编码的字符,很多时候,我们可能需要将这样的 Byte 数组转换为一个 String 。

** 解决方案 ** ** **

将一个包含 ASCII 编码字符的 Byte 数组转化为一个完整的 String ,可以使用如下的方法:

using System;


using System.Text;


 


public static string FromASCIIByteArray(byte[] characters)


{


    ASCIIEncoding encoding = new ASCIIEncoding( );


    string constructedString = encoding.GetString(characters);


    return (constructedString);

}


将一个包含 Unicode 编码字符的 Byte 数组转化为一个完整的 String ,可以使用如下的方法:

public static string FromUnicodeByteArray(byte[] characters)


{


    UnicodeEncoding encoding = new UnicodeEncoding( );


    string constructedString = encoding.GetString(characters);


    return (constructedString);

}


** 讨论 ** ** **

ASCIIEncoding 类的 GetString 方法可以将 byte 数组中的 7-BitsASCII 字符转换为一个 String ;任何大于 127 的值将被转化为两个字符。在 System.Text 命名空间中你可以找到 ASCIIEncoding 类,查找该类的 GetString 函数你还可以发现这个函数有多种重载方式以支持一些附加的参数。这个方法的重载版本还可以将一个 Byte 数组中的一部分字符转化为 String 。

将 Byte 数组转化为 String 的 GetString 方法可以在 System.Text 命名空间的 UnicodeEncoding 类中找到,该方法将包含 16-bitsUnicode 字符的 Byte 数组转化为 String 。同 ASCIIEncoding 类的 GetString 方法一样,该方法也包含一个将 Byte 数组中的特定部分转化为 String 的重载版本。

** 参考 ** ** **

要想了解更多的知识,可以参见 MSDN 文档

Published At
Categories with Web编程
Tagged with
comments powered by Disqus