赞
踩
demo源码:
-
- #include <QApplication>
- #include <QDebug>
- #include <QByteArray>
-
- // 头
- typedef struct tagEXT_HEADER
- {
- unsigned short type = 0x5642;
- }EXT_HEADER;
-
- // 数据包格式
- typedef struct tagMsgFormat
- {
- EXT_HEADER header;
- uint8_t msgId = 0x00;
- uint8_t msgNum= 0;
- uint16_t payloadLen = 0;
- // payload; // 长度不固定
- }MsgFormat;
-
- int main(int argc, char *argv[])
- {
- // 创建结构体数据
- EXT_HEADER header;
- MsgFormat format;
- format.msgId = 0x20;
- format.msgNum= 99;
- format.payloadLen = 16;
-
- // 直接导入QByteArray数据
- QByteArray data = QByteArray::fromStdString("\x01\x02\x03\x04\x05\x06");
- qDebug()<< "data:" << data.toHex();
-
- // 结构体转QByteArray数据
- QByteArray frame = QByteArray((char *)&header, sizeof(EXT_HEADER));
- qDebug()<< "frame:" << frame.toHex();
-
- // 修改结构体数据,然后转QByteArray数据
- header.type = 0x3412;
- QByteArray frame2 = QByteArray((char *)&header, sizeof(EXT_HEADER));
- qDebug()<< "frame2:" << frame2.toHex();
-
- // 嵌套式结构体转QByteArray数据
- QByteArray frame3 = QByteArray((char *)&format, sizeof(MsgFormat));
- qDebug()<< "frame3:" << frame3.toHex();
-
- // QByteArray数据转嵌套式结构体
- MsgFormat *cmd = (MsgFormat*)frame3.data();
- qDebug()<<"";
- qDebug()<<"frame3转为结构体之后的数据:";
- qDebug()<< "header:" << cmd->header.type;
- qDebug()<< "msgId:" << (uint8_t)(cmd->msgId);
- qDebug()<< "msgNum:" << cmd->msgNum;
- qDebug()<< "palyloadLen:" << cmd->payloadLen;
-
- // QByteArray数据只取帧头
- EXT_HEADER *cmdHeader = (EXT_HEADER*)frame3.data();
- qDebug()<< "header:" << cmdHeader->type;
-
- return 0;
- }
打印结果:
- data: "010203040506"
- frame: "4256"
- frame2: "1234"
- frame3: "425620631000"
-
- frame3转为结构体之后的数据:
- header: 22082
- msgId: 32
- msgNum: 99
- palyloadLen: 16
- header: 22082
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。