例如从一个输入框输入: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(' '));
}
效果: