天天看点

QCAD 中文编码问题

dxf

文件为文本文件,中文编码可能是

utf-8

编码,也有可能是

GBK

编码。

QCAD

使用

Qt

开发环境,字符串统一按照

utf-8

编码解码,

所以解析

dxf

文件时对字符串首先按照

utf-8

转码,如果转码失败则按照

GBK

转码。

QString decode(const std::string& str) {
    //GBK UTF-8->Unicode
    QByteArray data=QByteArray::fromStdString(str);
    QTextCodec::ConverterState state;
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QString str_tmp=codec->toUnicode(data.constData(),data.size(),&state);
    if(state.invalidChars>0){
        str_tmp=QTextCodec::codecForName("GBK")->toUnicode(data);
    }else{
        str_tmp=data;
    }
    return RDxfServices::parseUnicode(str_tmp);
}

           

使用

QString

类进行编码转换

QString 类包含了大量关于文本字符串编码转换的函数,涉及之前提到的 UTF-8(变长)、UTF-16、UTF-32、本地语言编码 Local8Bit(多字节编码),
还有标准 C++ 的普通字符串 StdString 和宽字符串 StdWString,
对于其他编码转为 QString,采用的是 QString::from* 静态公有成员函数,
这些静态函数返回一个转换好的 QString 对象以供使用。
与之对应的是 QString 类对象的 to* 函数,
QString 对象可以调用这些 to* 函数转出为其他编码格式的字符串。
           
from to desc
fromLocal8Bit toLocal8Bit 与操作系统及本地化语言相关,Linux 一般是 UTF-8 字符串,Windows 一般是 ANSI 多字节编码字符串。
fromUtf8 toUtf8 与 UTF-8 编码的字符串相互转换。
fromUtf16 utf16 和unicode 与 UTF-16(UCS2)编码的字符串互相转换,utf16 函数与 unicode 函数功能一样, 注意没有 to 前缀,因为 QString 运行时的内码就是 UTF-16,字符的双字节采用主机字节序。
fromUcs4 toUcs4 与 UTF-32(UCS4)编码的字符串互相转换,一个字符用四个字节编码,占空间多,应用较少。
fromStdString toStdString 与 std::string 对象互相转换,因为 C++11 规定标准字符串 std::string 使用 UTF-8 编码,这对函数功能与上面 **Utf8 转码函数相同。
fromStdWString toStdWString 与 std::wstring 对象相互转换,在 Linux 系统里宽字符是四字节的 UTF-32,在 Windows 系统里宽字符是两字节的 UTF-16。因为不同平台有歧义,不建议使用。

继续阅读