2012-08-17 66 views
0

返回一个多字节如果我编码以下字符串为UTF8:编码欧洲字符

咖啡厅

它返回5个字节,而不是4,我想它如果可能的话,返回4个字节。

Encoding encoding = Encoding.UTF8; 
string testString = "café"; 
Byte[] bytes = encoding.GetBytes(testString); 

返回:

[0] 99 
[1] 97 
[2] 102 
[3] 195 
[4] 169 

而 “网吧” 只返回4个字节。

+1

?你的期望是什么?你期望UTF8将“é”转换为“e”吗? – 2012-08-17 00:15:49

回答

0

端上变换UTF8ISO8859-1和它现在返回4个字节,而不是5

Encoding utf8 = Encoding.UTF8; 
string testString = "café"; 
byte[] utfBytes = utf8.GetBytes(testString); // 5 bytes 

Encoding iso = Encoding.GetEncoding("ISO-8859-1"); 
byte[] isoBytes = iso.GetBytes(testString); // 4 bytes 
byte[] convertedUtf8Bytes = Encoding.Convert(utf8, iso, utfBytes); // 4 bytes 

string msg = iso.GetString(isoBytes); 
string msgConverted = iso.GetString(convertedUtf8Bytes); 

Console.WriteLine(msg); 
Console.WriteLine(msgConverted); 

输出:

咖啡厅

咖啡馆

3

你不能用正常的编码方案。

您需要创建一个自定义编码与所需的代码页,像这样:

Encoding encoding = Encoding.GetEncoding(437); 
byte[] bytes = encoding.GetBytes("café"); 

输出:

{ 99, 97, 102, 130 } 

E为code page 437 130。

假设你将要解码它,你需要用相同的编码来解码它。否则,你会得到奇怪的结果。

3

é是Unicode U + 00E9。 Unicode字符U + 0080到U + 07FF在UTF8中占用两个字节。有关更多详细信息,请参见http://en.wikipedia.org/wiki/Utf8

如果你只想要4个字节,那么你就不能使用UTF8。理论上你可以使用ISO 8859-1这是一个单字节字符编码。