QT 串口通信 數據16進制發送


在QT中進行串口通信時,很多情況要用到發送16進制的數據。從網上找來了一段代碼測試能用:

  static QByteArray QString2Hex(QString str) 
{
  QByteArray senddata; 
int hexdata,lowhexdata;       
  int hexdatalen = 0;  
       int len = str.length();
 senddata.resize(len/2);      
   char lstr,hstr; 
 for(int i=0; i<len; ) 
 {
    hstr=str[i].toAscii(); 
   if(hstr == ' ') 
   {
     i++; 
     continue;
   }
   i++;          
   if(i >= len) 
       break; 
   lstr = str[i].toAscii(); 
    hexdata = ConvertHexChar(hstr); 
   lowhexdata = ConvertHexChar(lstr);        
    if((hexdata == 16) || (lowhexdata == 16)) 
      break; 
   else
     hexdata = hexdata*16+lowhexdata; 
    i++; 
    senddata[hexdatalen] = (char)hexdata; 
    hexdatalen++; 
 } 
  senddata.resize(hexdatalen);     
    return senddata; 
}


static char ConvertHexChar(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);
}

上面的是轉換函數,寫入的時候像下面這樣寫就行了
QByteArray senddata = Widget::QString2Hex(ui->lineEdit->text());      //轉換為16進制
com->write(senddata);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM