【问题标题】:Incorrect output for UTF8 conversion using iconv使用 iconv 进行 UTF8 转换的输出不正确
【发布时间】:2017-12-11 18:14:29
【问题描述】:

我正在尝试在 Linux 上将 ISO-8859-1 编码的字符串转换为 UTF-8。我正在使用 iconv 函数在 C++ 中执行此操作。这是我的代码:

//Conversion from ISO-8859-1 to UTF-8
iconv_t cd = iconv_open("UTF-8","ISO-8859-1");

char *input = "€"; // the byte value is 128 in ISO-8859-1
char *inputbuf= input;
size_t inputSize=1;

char *output = (char*)malloc(inputSize*4); // maximum size of a character in UTF8 is 4
char *outputbuf = output;
size_t outputSize = inputSize*4;

//Conversion Function
iconv (cd, &inputbuf, &inputSize, &outputbuf, &outputSize);

//Display input bytes(ISO-8859-1)
cout << "input bytes(ISO-8859-1):"
for (int i=0; i<inputSize; i++)
{
    cout <<(int) *(input+i) << ", ";
}
cout<< std::endl;

//Display Converted bytes(UTF-8)
cout << "output bytes(UTF-8):"
for (int i=0; i<outputSize; i++) //displaying all the 4 bytes allocated
{
    cout <<(int) *(output+i) << ", ";
}
cout<< std::endl;
iconv(cd);

这是我观察到的输出:

input bytes(ISO-8859-1): 128
output bytes(UTF-8): 194, 128, 0, 0

如您所见,输出 UTF-8 转换后的字节为 194,128。但是,预期的 UTF-8 输出为 226,130,172。我验证了任何 iconv 函数都没有抛出错误。

谁能帮我弄清楚我是否在这里遗漏了什么?

【问题讨论】:

  • 根据this table,代码128在ISO 8859-1代码页中未定义
  • 不是 ISO-8859-1 中的字节 128 (0x80)。事实上,字节 0x80 在 ISO-8859-1 中是未分配的。您正在考虑Windows-1252(或其他类似的字符集),它在字节0x80 中确实有(但在所有支持的字符集中并不总是0x80)。 Windows-1252 通常被误认为是 ISO-8859-1。
  • @YSC: ISO-8859-15 编码为字节 164 (0xA4)。

标签: c++ utf-8 iconv


【解决方案1】:

这是 iconv 的一个错误,因为 0xc2 0x80code point U+0080 glyph <control> 的有效 utf-8 序列。

这个字形经常被误认为是在 UTF-8 中编码为 0xe2 0x82 0xacglyph EURO SIGN, code point U+20AC

【讨论】:

  • 嗯,我对它的关注越多,我就越质疑我的结论...... ISO-8859-1 有欧元符号字形吗? ISO-8859-15 确实可以,但是...
  • ISO-8859-1 ("Latin-1") 和 ISO-8859-15 ("Latin-9") 的区别在于后者有 € 符号,而前任的。所以这不是 iconv 中的错误,我会说。
  • 不,ISO-8859-1 没有欧元符号。 ISO-8859-15 和 Windows-1252 是 ISO-8859-1 的分支,增加了欧元(以及其他)。
  • @lenz 谢谢你们。无论如何,我仍然保留我的答案,仍然是 iconv 的错误。
  • @YSC: ISO-8859-15 编码为 0xA4,而不是 0x80
【解决方案2】:

您可以为此使用 utfcpp 库:http://utfcpp.sourceforge.net/ 或 Boost.Locale

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 2015-10-28
    • 1970-01-01
    相关资源
    最近更新 更多