.net环境中的字符编码相关的操作类说明

在我们的程序中经常会有关于ASCII码,unicode, utf8等等多种字符编码的互换操作。虽然可以使用windows中的API函数实现,但在dotNet环境中却有更简单便捷的类来完成这项工作。

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

针对公共语言运行库的应用程序使用编码将字符表式形式从本机字符方案映射至其他方案。应用程序使用解码将字符从非本机方案映射至本机方案。下表列出了 tabindex="0" keywords="frlrfSystemText">System.Text 命名空间中对字符进行编码和解码的最常用的类。

字符方案 解释
ASCII 编码 tabindex="0" keywords="frlrfSystemTextASCIIEncodingClassTopic">System.Text.ASCIIEncoding 将字符与 ASCII 字符相互转换。
多种编码 tabindex="0" keywords="frlrfSystemTextEncodingClassTopic">System.Text.Encoding 将字符与 tabindex="0" keywords="frlrfSystemTextEncodingClassConvertTopic">Convert 方法中指定的各种编码相互转换。
UTF-16 Unicode 编码 tabindex="0" keywords="frlrfSystemTextUnicodeEncodingClassTopic">System.Text.UnicodeEncoding 在其他编码与 UTF-16 编码之间进行转换。此方案将字符表示为 16 位整数。
UTF-8 Unicode 编码 tabindex="0" keywords="frlrfSystemTextUTF8EncodingClassTopic">System.Text.UTF8Encoding 在其他编码与 UTF-8 编码之间进行转换。此宽度可变编码方案用一至四个字节表示字符。

下列代码示例使用 tabindex="0" keywords="frlrfSystemTextASCIIEncodingClassGetBytesTopic">ASCIIEncoding.GetBytes 方法将 Unicode 字符串转换为字节数组。数组中每个字节表示字符串中该位置字母的 ASCII 值。

[Visual Basic]
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

[C#]
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 类将前面的字节数组转换为字符数组。 tabindex="0" keywords="frlrfSystemTextASCIIEncodingClassGetCharsTopic">GetChars 方法用来解码字节数组。

[Visual Basic]
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

[C#]
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. 文本显示到控制台。

发布了30 篇原创文章 · 获赞 2 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/khzide/article/details/502940