首页 > 其他 > 详细

QT 串口通信 数据16进制发送

时间:2014-08-31 21:14:21      阅读:339      评论:0      收藏:0      [点我收藏+]

在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);

QT 串口通信 数据16进制发送

原文:http://www.cnblogs.com/yibanshouxi/p/3948105.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!