將Byte數組轉化為String-.NET教程,C#語言

來源:互聯網
上載者:User
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的重載版本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.