在C ++中从UTF-8转换为ISO8859-15

时间:2018-11-12 20:14:15

标签: c++ string encoding utf-8 iso-8859-15

我想在C / C ++中进行从UTF-8到ISO 8859-15的转换,而无需包含其他库。

我该如何实现?

我发现以下代码适用于ISO 8859-1,但是我不确定如何处理ISO 8859-15和ISO 8859-1(https://en.wikipedia.org/wiki/ISO/IEC_8859-15)之间的区别:

std::string UTF8toISO8859_1(const char * in) {
    std::string out;
    if (in == NULL)
        return out;

    unsigned int codepoint;
    while (*in != 0) {
        unsigned char ch = static_cast<unsigned char>(*in);
        if (ch <= 0x7f)
            codepoint = ch;
        else if (ch <= 0xbf)
            codepoint = (codepoint << 6) | (ch & 0x3f);
        else if (ch <= 0xdf)
            codepoint = ch & 0x1f;
        else if (ch <= 0xef)
            codepoint = ch & 0x0f;
        else
            codepoint = ch & 0x07;
        ++in;
        if (((*in & 0xc0) != 0x80) && (codepoint <= 0x10ffff)) {
            if (codepoint <= 255) {
                out.append(1, static_cast<char>(codepoint));
            }
            else {
                out.append("?");
            }
        }
    }
    return out;
}

1 个答案:

答案 0 :(得分:2)

我喜欢这段代码。太短了。大多数代码只处理将多字节序列解码为代码点。编码点解码后,转换为ISO-8859-1非常简单:

  • 如果小于或等于255,则它也是有效的ISO-8859-1字符:UIView
  • 如果没有,则不能在ISO-8859-1中表示,并用问号代替:out.append(1, static_cast<char>(codepoint));

因此,要使其适用于ISO-8859-15,需要更多代码来处理引入ISO-8859-15时被替换的字符(请参见Comparing ISO-8859-1 and ISO-8859-15)。不幸的是,它大大增加了代码大小。

下面的代码应该很容易理解。如果这是主要问题,可以对其进行优化以获得更好的性能。

out.append("?");