3

我需要根据已知的文件编码和所需的输出编码来决定何时(不)转换文本文件。

如果文本是US-ASCII,如果输出编码是ASCII,UTF-8,Latin1,我不需要转换它...
显然我需要将US-ASCII文件转换为UTF-16或UTF-32 .

标准编码列表位于
http://www.iana.org/assignments/character-sets/character-sets.xml

如果出现以下情况,则需要进行转换:

  • 最小字符大小 > 1 字节或
  • 前 127 个代码点与 US-ASCII 不同。

我想知道:

  • 是否有类似的列表,其中包含有关每种编码实现的详细信息(字节长度、ASCII 兼容性)?

编辑
我已经找到了问题的答案

  • 所有基于 8 位或可变 8 位的编解码器都是 ASCII 的超集吗?
    • 换句话说:US-ASCII 可以解释为任何基于 8 位或可变 8 位的编码吗?

此处:不是 ASCII 超集的字符集
相反,了解以下内容会有所帮助:

  • 是否有作为 ASCII 超集的字符集列表?

这看起来很有希望:
mime.charsets - 作为 ASCII 超集的字符集列表
但我找不到实际的 mime.charsets 文件。

4

1 回答 1

3

另一种方法是解码给定编码中的字节 0x00 - 0x7F,并检查字符是否与 ASCII 匹配。例如,在 Python 3.x 中:

def is_ascii_superset(encoding):
    for codepoint in range(128):
       if bytes([codepoint]).decode(encoding, 'ignore') != chr(codepoint):
           return False
    return True

这给出了:

>>> is_ascii_superset('US-ASCII')
True
>>> is_ascii_superset('windows-1252')
True
>>> is_ascii_superset('ISO-8859-15')
True
>>> is_ascii_superset('UTF-8')
True
>>> is_ascii_superset('UTF-16')
False
>>> is_ascii_superset('IBM500') # a variant of EBCDIC
False

编辑:获取 C++ 中 Qt 版本支持的每种编码的 US-ASCII 兼容性:

#include <QTextCodec>
#include <QMap>

typedef enum
{
    eQtCodecUndefined,
    eQtCodecAsciiIncompatible,
    eQtCodecAsciiCompatible,
} tQtCodecType;

QMap<QByteArray, tQtCodecType> QtCodecTypes()
{
    QMap<QByteArray, tQtCodecType> CodecTypes;
    // How to test Qt's interpretation of ASCII data?
    QList<QByteArray> available = QTextCodec::availableCodecs();
    QTextCodec *referenceCodec = QTextCodec::codecForName("UTF-8"); // because Qt has no US-ASCII, but we only test bytes 0-127 and UTF-8 is a superset of US-ASCII
    if(referenceCodec == 0)
    {
        qDebug("Unable to get reference codec 'UTF-8'");
        return CodecTypes;
    }
    for(int i = 0; i < available.count(); i++)
    {
        const QByteArray name = available.at(i);
        QTextCodec *currCodec = QTextCodec::codecForName(name);
        if(currCodec == NULL)
        {
            qDebug("Unable to get codec for '%s'", qPrintable(QString(name)));
            CodecTypes.insert(name, eQtCodecUndefined);
            continue;
        }
        tQtCodecType type = eQtCodecAsciiCompatible;
        for(uchar j = 0; j < 128; j++) // UTF-8 == US-ASCII in the lower 7 bit
        {
            const char c = (char)j; // character to test < 2^8
            QString sRef, sTest;
            sRef = referenceCodec->toUnicode(&c, 1); // convert character to UTF-16 (QString internal) assuming it is ASCII (via UTF-8)
            sTest = currCodec->toUnicode(&c, 1); // convert character to UTF-16 assuming it is of type [currCodec]
            if(sRef != sTest) // compare both UTF-16 representations -> if they are equal, these codecs are transparent for Qt
            {
                type = eQtCodecAsciiIncompatible;
                break;
            }
        }
        CodecTypes.insert(name, type);
    }

    return CodecTypes;
}
于 2013-10-30T22:43:18.443 回答