C#字節數組轉換成字符串

https://www.cnblogs.com/Asa-Zhu/archive/2012/11/08/2761137.htmlhtml

若是還想從 System.String 類中找到方法進行字符串和字節數組之間的轉換,恐怕你會失望了。爲了進行這樣的轉換,咱們不得不借助另外一個類:System.Text.Encoding。該類提供了 bye[] GetBytes(string) 方法將字符串轉換成字節數組,還提供了 string GetString(byte[]) 方法將C#字節數組轉換成字符串。

以下字符串與字節數組互換的例子:數組

byte[] msg = Encoding.Unicode.GetBytes(textBox1.Text);
            this.label1.Text = Encoding.Unicode.GetString(msg);
函數

 

  System.Text.Encoding 相似乎沒有可用的構造函數,但咱們能夠找到幾個默認的 Encoding,即 Encoding.Default(獲取系統的當前 ANSI 代碼頁的編碼)、Encoding.ASCII(獲取 7 位 ASCII 字符集的編碼)、Encoding.Unicode(獲取採用 Little-Endian 字節順序的 Unicode 格式的編碼)、Encoding.UTF7(獲取 UTF-7 格式的編碼)、Encoding.UTF8(獲取 UTF-8 格式的編碼) 等。這裏主要說說 Encoding.Default 和 Encoding.Unicode 用於轉換的區別。this

 

  在字符串轉換到字節數組的過程當中,Encoding.Default 會將每一個單字節字符,如半角英文,而把每一個雙字節字符,如漢字。而 Encoding.Unicode 則會將它們都轉換成兩個字節。咱們能夠經過下列簡單的瞭解一下轉換的方法,以及使用 Encoding.Default 和 Encodeing.Unicode 的區別:編碼

 

private void TestStringBytes() {  code

string s = "C#語言";  htm

byte[] b1 = System.Text.Encoding.Default.GetBytes(s);  blog

byte[] b2 = System.Text.Encoding.Unicode.GetBytes(s);  字符串

string t1 = "", t2 = "";  string

foreach (byte b in b1) {  

t1 += b.ToString("") + " ";  

}  

foreach (byte b in b2) {  

t2 += b.ToString("") + " ";  

}  

this.textBox1.Text = "";  

this.textBox1.AppendText("b1.Length = " + b1.Length + "\n");  

this.textBox1.AppendText(t1 + "\n");  

this.textBox1.AppendText("b2.Length = " + b2.Length + "\n");  

this.textBox1.AppendText(t2 + "\n");  

} 

 

  運行結果以下,不說詳述,相信你們已經明白了。

 

b1.Length = 6 

67 35 211 239 209 212  

b2.Length = 8 

67 0 35 0 237 139 0 138  

 

  將C#字節數組轉換成字符串,使用 Encoding 類的 string GetString(byte[]) 或 string GetString(byte[], int, int) 方法,具體使用何種 Encoding 仍是由編碼決定。在 TestStringBytes() 函數中添加以下語句做爲實例:

 

byte[] bs = {97, 98, 99, 100, 101, 102};  

string ss = System.Text.Encoding.ASCII.GetString(bs);  

this.textBox1.AppendText("The string is: " + ss + "\n"); 

 

  運行結果爲:The string is: abcdef

相關文章
相關標籤/搜索