QT 识别文件编码(gbk和utf-8)

说明:
对字符串首字节进行转码,判断是gbk还是utf-8,

QString Widget::GetCorrectUnicode(const QByteArray &ba)
{
    QTextCodec::ConverterState state;
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    //调用utf8转unicode的方式转码,获取无效字符
    QString text = codec->toUnicode( ba.constData(), 1, &state);

    qDebug() <<state.invalidChars;
    //存在无效字符则是GBK,转码后返回
    if (state.invalidChars)
    {
        text = QTextCodec::codecForName( "GBK" )->toUnicode(ba);
    }
    else
    {
        text =  codec->toUnicode(ba);
    }
    return text;
}

你可能感兴趣的:(qt,qt)