Share via


为基类型编码

字符是可使用多种不同字符方案或代码页来表示的抽象实体。 例如,Unicode UTF-16 编码将字符表示为 16 位整数序列,而 Unicode UTF-8 编码则将相同的字符表示为 8 位字节序列。 公共语言运行时使用 Unicode UTF-16(Unicode 转换格式,16 位编码形式)表示字符。

针对公共语言运行时的应用程序使用编码将字符表式形式从本机字符方案映射至其他方案。 应用程序使用解码将字符从非本机方案映射至本机方案。 下表列出了 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

其他资源

使用基类型