直接貼代碼:
/*
* @param [int]str 字符串
* @param [int]size 字符串長度
* @param [out]qstring QString 引用
*/
QString bytesToHex( char* str, int size, QString &qstring)
{
for (int i = 0; i < size; i++)
{
char tempOne = (unsigned char)str[i] >> 4;
if (tempOne >= 0x0a)
{
tempOne = 0x41 - 0x0A;
}
else
{
tempOne = tempOne + 0x30;
}
char tempTwo = (unsigned char)str[i] & 0xF;
if (tempTwo >= 0x0a)
{
tempTwo = tempTwo + 0x41 - 0x0a;
}
else
{
tempTwo = tempTwo + 0x30;
}
qstring.append(tempOne);
qstring.append(tempTwo);
if (i == size - 1)
{
continue;
}
qstring.append(" ");
}
//qDebug() << "qstring:" << qstring;
return qstring;
}
char* str = "this is string";
QString qstring ;
qDebug()<<"string:" << bytesToHex(str , strlen(str), qstring);
輸出結果爲:74 68 69 73 20 69 73 20 73 74 72 69 6E 67