16进制QString和unsigned char数组互相转换

 17位16进制mac字符串转为6位字节数组

demo: unsigned char* byteArr = hexStringToByteArray(QString("A1-B2-C3-D4-E5-F6")).data();

QVector hexStringToByteArray(const QString& strMac)
{
    QVector vecMac;
    unsigned char* p = vecMac.data();
    if (strMac.size() != 17)
    {
        return vecMac;
    }
    for (int i = 0; i < strMac.size(); i += 3)
    {
        QString num = strMac.mid(i, 2);
        bool ok = false;
        vecMac.push_back(num.toUInt(&ok, 16));
        if (!ok)
        {
            return QVector();
        }
    }
    return vecMac;
}

6位字节数组转17位16进制QString

demo:

QString s_font_code = QString("A1-B2-C3-D4-E5-F6");

QVector byteArr1 = hexStringToByteArray(s_font_code);

unsigned char* pByte1 = byteArr1.data();

QString byteArrayToHexString(unsigned char* str)
{
    QString result = "";
    //int lengthOfString = strlen(reinterpret_cast(str));
    int lengthOfString = 6;

    QString s;
    for (int i = 0; i < lengthOfString; ++i)
    {
        s = QString("%1").arg(str[i], 0, 16);

        // account for single-digit hex values (always must serialize as two digits)
        if (s.length() == 1)
            result.append("0");

        result.append(s.toUpper());
        result.append('-');
    }

    //删除最后一个'-'
    result.chop(1);

    return result;
}

 

你可能感兴趣的:(Qt,QT)