【问题标题】:Encoding returning one more byte for european character编码为欧洲字符返回一个字节
【发布时间】:2012-08-17 00:10:22
【问题描述】:

如果我将以下字符串编码为 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

而“cafe”只返回 4 个字节。

【问题讨论】:

  • ?你的期望是什么?您希望 UTF8 将“é”转换为“e”吗?

标签: c# encoding utf-8


【解决方案1】:

é 是 Unicode U+00E9。 Unicode 字符 U+0080 到 U+07FF 在 UTF8 中占用两个字节。详情请见http://en.wikipedia.org/wiki/Utf8

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

【讨论】:

    【解决方案2】:

    你不能使用普通的编码方案。

    您需要使用所需的代码页创建自定义编码,如下所示:

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

    输出:

    { 99, 97, 102, 130 }
    

    é 在code page 437 中是 130。

    假设您要对其进行解码,则需要使用相同的编码对其进行解码。否则你会得到奇怪的结果。

    【讨论】:

      【解决方案3】:

      UTF-8 中的字符可以占用 1 到 6 个字节。因此,对于您的情况,“é”需要 2 个字节。 您可以在此处阅读有关 UTF-8 的更多信息:UTF-8, a transformation format of ISO 10646

      【讨论】:

        【解决方案4】:

        最终将 UTF8 转换为 ISO8859-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);
        

        输出:

        咖啡厅

        咖啡厅

        【讨论】:

          猜你喜欢
          • 2011-09-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-28
          • 1970-01-01
          • 1970-01-01
          • 2020-05-22
          相关资源
          最近更新 更多