QT字符编码转换,可用于中文内码传输

时间:2021-12-16 06:57:00

串口、TCP、UDP传输中文字符时,先将字符串转内码。客户端接收到数据后,将内码转为字符串就OK了

QByteArray CommonFunction::strToInterCode(constQString &str)//字符串转内码

{
    QString strName = str.toLocal8Bit();
    QByteArray code;
    code.append (strName);

    while(code.count()<8)
    {
        code.append (QByteArray::fromHex ("20"));
    }
    qDebug ()<<"string to intercode"<<QObject::tr("%1").arg (code.toHex ().data ());
    return code;
}

//内码转字符串,要求为双字节数
QString CommonFunction::interCodeToStr(const QByteArray &data)
{
    QString str;
    QByteArray temp;
    for(int i= 0;i<data.length();i+=2)
    {
        if(!(data[i] == 0x20 && data[i+1] == 0x20))
        {
            temp.append (data[i]);
            temp.append (data[i+1]);
        }
    }
    str = QString::fromLocal8Bit(temp);
    qDebug ()<< "intercode To string :"<<str;
    return str;
}

// 字符串转Unicode码
QByteArray CommonFunction::strToUniCode(const QString &str)
{
    // 这里传来的字符串一定要加tr,main函数里可以加 QTextCodec::setCodecForTr(QTextCodec::codecForLocale());

    QString stt = QObject::tr("%1").arg (str);

    QByteArray data;
    const QChar *q;
    QChar qtmp;
    int num;
    q=stt.unicode();
    int len=stt.count();
    for(int i=0;i<len;i++)
    {
        qtmp =(QChar)*q++;
        num= qtmp.unicode();

        quint8 hi = (quint8)(num >> 8);
        quint8 lo = (quint8)(num);
        data.append (hi);
        data.append (lo);
    }

    while(data.count () <8)
    {
        data.append (QByteArray::fromHex ("20"));
    }
    qDebug ()<<"string to unicode :"<<QObject::tr("%1").arg (data.toHex ().data ());
    return data;
}


//Unicode码转字符串
QString CommonFunction::uniCodeToStr(const QByteArray &data)
{
    QByteArray data_1;
    for(int i= 0;i<data.length ();i+=2)
    {
        if(!(data[i] == 0x20 && data[i+1] == 0x20))
        {
            data_1.append (data[i]);
            data_1.append (data[i+1]);
        }
    }
    QString str = data_1.toHex ().data ();
    int temp[400];

    QChar qchar[100];

    QString strOut;
    bool ok;
    int count=str.count();
    int len=count/4;
    for(int i=0;i<count;i+=4)
    {
        temp[i]=str.mid(i,4).toInt(&ok,16);//每四位转化为16进制整型
        qchar[i/4]=temp[i];
        QString str0(qchar, len);
        strOut=str0;
    }
    qDebug ()<<"unicode to string:"<<strOut;
    return strOut;
}

http://blog.csdn.net/liuguangzhou123/article/details/7478088