將基底型別編碼

字元是抽象實體 (Entity),可以用許多不同的字元配置或字碼頁 (Code Page) 來表示。 例如,Unicode UTF-16 編碼會將字元表示成一連串 16 位元的整數,而 Unicode UTF-8 則會將相同的字元表示成一連串 8 位元的位元組。 Common Language Runtime 會使用 Unicode UTF-16 (Unicode Transformation Format,16 位元的編碼格式) 來表示字元。

以 Common Language Runtime 為目標的應用程式會使用編碼方式,將字元表示從原生字元配置對應至其他配置。 應用程式會使用編碼方式,將字元從非原生配置對應至原生配置。 下表會列出在 System.Text 命名空間中最常用來將字元編碼和解碼的類別。

字元配置

類別

說明

ASCII 編碼方式

System.Text.ASCIIEncoding

轉換 ASCII 字元。

多重編碼

System.Text.Encoding

依照 Convert 方法中指定的方式轉換不同編碼的字元。

UTF-16 Unicode 編碼

System.Text.UnicodeEncoding

轉換 UTF-16 編碼。 這種配置方式會將字元表示成 16 位元的整數。

UTF-8 Unicode 編碼

System.Text.UTF8Encoding

轉換 UTF-8 編碼。 這種可變寬度的編碼配置方式會使用一到四個位元組來表示字元。

下列程式碼範例會使用 ASCIIEncoding.GetBytes 方法,將 Unicode 字串轉換成位元組陣列。 陣列中的每一個位元組各代表字串中該位置字母的 ASCII 值。

Dim MyString As String = "Encoding String."
Dim AE As New ASCIIEncoding()
Dim ByteArray As Byte() = AE.GetBytes(MyString)
Dim x as Integer
For x = 0 To ByteArray.Length - 1
   Console.Write("{0} ", ByteArray(x))
Next
string MyString = "Encoding String.";
ASCIIEncoding AE = new ASCIIEncoding();
byte[] ByteArray = AE.GetBytes(MyString);
for(int x = 0;x <= ByteArray.Length - 1; x++)
{
   Console.Write("{0} ", ByteArray[x]);
}

這個範例會將下列結果顯示在主控台上。 位元組 69 是 E 字元的 ASCII 值;位元組 110 是 n 字元的 ASCII 值,依此類推。

69 110 99 111 100 105 110 103 32 83 116 114 105 110 103 46

下列程式碼範例會使用 ASCIIEncoding 類別,將上面的位元組陣列轉換成字元陣列。 GetChars 方法是用來將位元組陣列解碼。

Dim AE As New ASCIIEncoding()
Dim ByteArray As Byte() = { 69, 110, 99, 111, 100, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 46 }
Dim CharArray As Char() = AE.GetChars(ByteArray)
Dim x As Integer
For x = 0 To CharArray.Length - 1
   Console.Write(CharArray(x))
Next
ASCIIEncoding AE = new ASCIIEncoding();
byte[] ByteArray = { 69, 110, 99, 111, 100, 105, 110, 103, 32, 83, 116, 114, 105, 110, 103, 46 };
char[] CharArray = AE.GetChars(ByteArray);
for(int x = 0;x <= CharArray.Length - 1; x++)
{
   Console.Write(CharArray[x]);
}

上述程式碼會將 Encoding String. 文字顯示在主控台上。

請參閱

參考

System.Text

System.Text.ASCIIEncoding

System.Text.Encoding

System.Text.UnicodeEncoding

System.Text.UTF7Encoding

System.Text.UTF8Encoding

其他資源

使用基底型別