打印

[NET精华教程] .net教程:将byte数组转化为string

.net教程:将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的重载版本。





TOP

返回顶部
AYBlue

Processed in 0.055484 second(s), 7 queries.

当前时区 GMT+8, 现在时间是 2009-1-8 14:59 京ICP备06054220号

清除 Cookies - 联系我们 - 163K.com - Archiver - WAP