如何在 C# 中將位元組陣列轉換為字串?
在 .Net 中,每個字串都有一個字元集和編碼。一種字元編碼告訴計算機如何將原始的零和一解釋為真正的字元。它通常透過將數字與字元配對來實現此目的。實際上,它是在對一組 Unicode 字元進行轉換生成一個位元組序列的過程。
我們可以使用 Encoding.GetString Method (Byte[]) 來將指定位元組陣列中的所有位元組解碼成字串。編碼類中還提供了多種其他解碼方案,比如 UTF8、Unicode、UTF32、ASCII 等。編碼類可在 System.Text 名稱空間中找到。
string result = Encoding.Default.GetString(byteArray);
示例
using System; using System.Text; namespace DemoApplication { public class Program { static void Main(string[] args) { byte[] byteArray = Encoding.Default.GetBytes("Hello World"); Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}"); string str = Encoding.Default.GetString(byteArray); Console.WriteLine($"String is: {str}"); Console.ReadLine(); } } }
輸出
上述程式碼的輸出為
Byte Array is: 72 101 108 108 111 32 87 111 114 108 100 String is: Hello World
需要指出的是,我們應當對兩個方向使用相同的編碼。例如,如果位元組陣列採用 ASCII 編碼,而我們嘗試使用 UTF32 獲得字串,我們則無法獲得需要的字串。
示例
using System; using System.Text; namespace DemoApplication { public class Program { static void Main(string[] args) { byte[] byteArray = Encoding.ASCII.GetBytes("Hello World"); Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}"); string str = Encoding.UTF32.GetString(byteArray); Console.WriteLine($"String is: {str}"); Console.ReadLine(); } } }
輸出
上述程式碼的輸出為
Byte Array is: 72 101 108 108 111 32 87 111 114 108 100 String is: ???
廣告