前言:Qt界面下,为了得到某个数据,将输入的16进制先转换成字符,经过一系列操作,再将字符串转化为16进制输出。
void MainWindow::on_pushButton_clicked()
{
int len = 0;
unsigned char checkSum[20] = {0};
unsigned char buff[300] = {0};
//RID
char* chRID = ui->lineEdit_RID->text().toLatin1().data(); //QString转char
char chRID_HexString[6];
hexstringToBytes(chRID,chRID_HexString,10);
memcpy(buff, chRID_HexString, 5);
//KeyID
char* chKetID = ui->lineEdit_KeyID->text().toLatin1().data();
char chKetID_HexString[2];
hexstringToBytes(chKetID,chKetID_HexString,2);
len += 5;
memcpy(buff + len, chKetID_HexString, 1);
len += 1;
//Module
char* chModule = ui->lineEdit_Module->text().toLatin1().data();
int moduleLenth = ui->lineEdit_Module->text().length();
if (moduleLenth %2 != 0)
{
QMessageBox::warning(this, "Error", "The length of Module is Error!");
return;
}
//ModuleLength
int num = ui->lineEdit_ModuleLength->text().toInt();
char chModule_HexString[num + 1];
hexstringToBytes(chModule,chModule_HexString,moduleLenth);
memcpy(buff + len, chModule_HexString, num);
len += num;
//Exponent
char* chExponent = ui->lineEdit_Exponent->text().toLatin1().data();
int numExponent = ui->lineEdit_ExponentLen->text().toInt();
char chExponent_hexString[numExponent+1];
int ExponentLength = ui->lineEdit_Exponent->text().length();
hexstringToBytes(chExponent,chExponent_hexString,ExponentLength);
memcpy(buff + len, chExponent_hexString, numExponent);
len += numExponent;
DEVICE_Hash(buff, len, checkSum);
char str1[41] = {};
bytesToHexstring(checkSum,20,str1,40);
QString str = QString(QLatin1String(str1)); char转QString
ui->lineEdit_CheckSum->setText(str);
}
//转16进制
void bytesToHexstring(unsigned char* bytes,int bytelength,char *hexstring,int hexstrlength)
{
char str2[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
for (int i=0,j=0;i<bytelength,j<hexstrlength;i++,j++)
{
int b;
b = 0x0f&(bytes[i]>>4);
char s1 = str2[b];
hexstring[j] = s1;
b = 0x0f & bytes[i];
char s2 = str2[b];
j++;
hexstring[j] = s2;
}
}
int hexcharToInt(char c)
{
if (c >= '0' && c <= '9') return (c - '0');
if (c >= 'A' && c <= 'F') return (c - 'A' + 10);
if (c >= 'a' && c <= 'f') return (c - 'a' + 10);
return 0;
}
void hexstringToBytes(char* hexstring,char* bytes,int hexlength)
{
for (int i=0 ; i <hexlength ; i+=2) {
bytes[i/2] = (char) ((hexcharToInt(hexstring[i]) << 4)
| hexcharToInt(hexstring[i+1]));
}
}