QT实现串口的十六进制发送


void MainWindow ::on_pushBUtton_clicked () //发送数据
{
        QString strTXData;
        QByteArray hexdata;
       // strTXData = ui->lineEdit->text().toAscii();//txTextEdit
        strTXData = ui->txTextEdit->toPlainText().toAscii();
        if(ui->txHexcheckBox->isChecked()==true)
        {
            QByteArray temp;
                QString strHex;
            //count1=stringToHex(strTXData,hexdata);
            stringToHex(strTXData,hexdata);
            myCom->write(hexdata);
            temp =hexdata;
            QDataStream out(&temp,QIODevice::ReadWrite);//将字节数组读入
            while(!out.atEnd()) {
                qint8 outChar = 0;
                out >> outChar;//每字节填充一次,直到结束
                QString str = QString("%1").arg(outChar&0xFF, 2, 16, QLatin1Char('0'));//十六进制的转换
                count1++;
                strHex += str;
 
  
            }
            ui->TxlineEdit->setText(QString::number(count1));
        }
……………………………………………………
int MainWindow::stringToHex(QString str,QByteArray &senddata)
{
    int hexdata,lowhexdata;
        int hexdatalen = 0;
        int len = str.length();
        senddata.resize(len/2);//
        char lstr,hstr;
        str[len]=' ';
        for(int i=0; i<len; )
        {
            hstr=str[i].toAscii();
            //if(hstr == 0x0a)
             //   continue;
            i++;
            lstr=str[i].toAscii();
 
  
            if(lstr == ' ')
            {
                lstr=hstr;
                hstr='0';
                i++;
            }
            else
            {
                i++;
                if(str[i]!=' ')
                {
 
  
                }
                else
                {
                    i++;
                }
            }
            if(i >= len+2)
               break;
            hexdata = ConverToHexChar(hstr);
            lowhexdata = ConverToHexChar(lstr);
            if((hexdata == 16) || (lowhexdata == 16))
                break;
           else
               hexdata = hexdata*16+lowhexdata;
            senddata[hexdatalen] = (char)hexdata;
            hexdatalen++;
        }
        senddata.resize(hexdatalen);
        return hexdatalen;
 
  
 
  
}
 
  
char MainWindow::ConverToHexChar(char ch)
{
    if((ch >= '0') && (ch <= '9'))
            return ch-0x30;
        else if((ch >= 'A') && (ch <= 'F'))
            return ch-'A'+10;
        else if((ch >= 'a') && (ch <= 'f'))
            return ch-'a'+10;
        else return (-1);
}
 
  
 
 

你可能感兴趣的:(QT)