qt 字符串转换成十六进制

例如从一个输入框输入:31 32 33 34字符串,在程序中转换成十六进制0x31 0x32 0x33 0x34

应用:如求数据的crc码,先从输入框输入十六进制数据,需将字符串转换成十六进制,再对此序列数据进行crc计算,再将数据和crc码输出到输出框中

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QArrayData>
#include <QDebug>


#define crc_mul 0x1021  //生成多项式

unsigned int msg_crc(unsigned char *ptr, unsigned char len)
{
    unsigned char i;
    unsigned int crc=0;
    while(len-- != 0)
    {
        for(i=0x80; i!=0; i>>=1)
        {
            if((crc&0x8000)!=0)
            {
               crc<<=1;
               crc^=(crc_mul);
            }else{
               crc<<=1;
            }
            if((*ptr&i)!=0)
            {
               crc ^= (crc_mul);
            }
        }
        ptr ++;
    }
    return (crc);
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->inputButton,SIGNAL(clicked()),
                this,SLOT(calc_and_display_crc()));
}

MainWindow::~MainWindow()
{
    delete ui;
}




void string_to_hex(QString hex,QByteArray &qbyte)
{

    hex=hex.trimmed();

    QStringList sl=hex.split(" ");
    foreach(QString s,sl)
    {
        if(!s.isEmpty())
            qbyte.append((char)s.toInt(0,16)&0xFF);
    }

}

void MainWindow:: calc_and_display_crc(void)
{
    QByteArray aa,bb;
    QString str0;
    QString str1;
    bool ok;
    unsigned char crcBuf[50];
    unsigned short crc;
    int i;


    str0 = ui->inputDataEdit->text();

    string_to_hex(str0,aa);
    for(i=0;i<aa.size(); i++)
    {
        crcBuf[i] = aa[i];
    }
    crc = msg_crc(crcBuf,i);
    str1 = QString::number(crc);
    qDebug()<<str1;
    aa[i] = crc>>8;
    aa[i+1] = crc &0x00ff;

    //aa = str0.toLocal8Bit();

    ui->disQtext->setText(aa.toHex(' '));


}

效果:

   

 

  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值