QT串口程序已16进制接受和发送数据

以16进制接受数据:

//读取串口缓冲区的所有数据给临时变量temp
    QByteArray temp = MyCom->readAll();
   
    QDataStream out(&temp,QIODevice::ReadWrite);    //将字节数组读入
    
    while(!out.atEnd())
    {
        qint8 outChar = 0;
        out>>outChar;   //每字节填充一次,直到结束
        //十六进制的转换
        QString str = QString("%1").arg(outChar&0xFF,2,16,QLatin1Char('0'));
        ui->textBrowser->insertPlainText(str);
    }
    
    ui->textBrowser->insertPlainText("\n");
以16进制发送数据:

    QString str = ui->lineEdit->text();//从LineEdit得到字符串

    QByteArray senddata;

    StringToHex(str,senddata);//将str字符串转换为16进制的形式

    MyCom->write(senddata);//发送到串口

void Widget::StringToHex(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)
            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);
}

char Widget::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);
}


你可能感兴趣的:(Qt)