一、qt Modbus crc
quint16 MasterModbus::getCrc(QByteArray arr)
{
quint16 res = 0xffff;
int index=0;
while(index<arr.size())
{
res ^= (quint8)arr[index];
for(int i = 0; i < 8; i ++)
{
if(res & 0x01)
{
res = (res >> 1) ^ 0xa001;
}
else
{
res = res >> 1;
}
}
index++;
}
res = ((res & 0xff) << 8) | (res >> 8);
return res;
}
quint16 MasterModbus::getCrc(quint8 *bytes, int len)
{
quint16 res = 0xffff;
while(len --)
{
res ^= *bytes ++;
for(int i = 0; i < 8; i ++)
{
if(res & 0x01)
{
res = (res >> 1) ^ 0xa001;
}
else
{
res = res >> 1;
}
}
}
res = ((res & 0xff) << 8) | (res >> 8);
return res;
}
二、CCSDS校验
生成多项式如下
g(x) = x^16 + x^12 + x^5 + x^1
uint16_t Widget::getCrc(QByteArray bytes)
{
uint16_t wCRCin = 0xFFFF;
uint16_t wCPoly = 0x1021;
uchar wChar = 0;
int index = 0;
while (index<bytes.size())
{
wChar = bytes[index];
wCRCin ^= (wChar << 8);
for (int i = 0; i < 8; i++)
{
if (wCRCin & 0x8000)
{
wCRCin = (wCRCin << 1) ^ wCPoly;
}
else
{
wCRCin = wCRCin << 1;
}
}
index++;
}
return (wCRCin);
}
三、异或校验
quint16 BccCRC(quint8 *data,quint16 len){
quint16 bcc=0;
for(; len>0;len--){
bcc ^= *data;
data++;
}
return ((bcc & 0xff) << 8) | (bcc >> 8);
}
quint16 BccCRC(QByteArray arr){
quint16 bcc = 0;
int index = 0;
int len = 0;
len = arr.length ();
while (len--) {
bcc ^= (quint8)arr.at (index);
index++;
}
return ((bcc & 0xff) << 8) | (bcc >> 8);
}
Qt用法举例[异或校验]
QByteArray dataCode;
quint16 crcRes = 0;
dataCode.append (ui->lEdtData->text ());
crcRes = crc.BccCRC (dataCode.toHex ());
自己实践的结果
在线生成器生成的结果
四、数据显示
Ⅰ、十六进制显示
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QByteArray arr("1234");
bool isTransformSuccessful = false;
qDebug()<<"isTransformSuccessful"<<isTransformSuccessful<<arr.toInt (&isTransformSuccessful,16);
return a.exec();
}
打印结果
isTransformSuccessful true 4660
Ⅱ、十进制显示
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QByteArray arr("1234");
bool isTransformSuccessful = false;
qDebug()<<"isTransformSuccessful"<<isTransformSuccessful<<arr.toInt (&isTransformSuccessful,10);
return a.exec();
}
打印结果
isTransformSuccessful true 1234
分割显示
低版本的qt可能不支持,我测试使用的版本为qt5.14.2版本
分割显示
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QByteArray arr("1234");
qDebug()<<arr.toHex (' ');
qDebug()<<arr.toHex ('.');
qDebug()<<arr.toHex (':');
qDebug()<<arr.toHex ('-');
return a.exec();
}
打印结果
“31 32 33 34”
“31.32.33.34”
“31:32:33:34”
“31-32-33-34”