在编写dbc报文的协议解析时,使用位域运算和联合体的组合,能够巧妙解决字段解析问题,代码看起来整洁又健壮。
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
typedef union tagCoreCalibrationSPCprotocol
{
uint32_t ulData[4];
struct
{
uint32_t ulData[3];
uint32_t ulTimeStamp;
}sTimeStamp;
struct
{
uint32_t CLB_SPC_Zero_byte :8;
uint32_t Reserved_1 :24;
uint32_t CLB_SPC_Header_CRC :32;
uint32_t CLB_SPC_Protocol_Version :8;
uint32_t CLB_SPC_Sync_ID :8;
uint32_t CLB_SPC_Status :2;
uint32_t CLB_SPC_Progress :7;
uint32_t CLB_SPC_Error :2;
uint32_t CLB_SPC_Session_Number :3;
uint32_t CLB_SPC_Frame_Valid :1;
uint32_t Reserved_2 :1;
}sMsg;
}CORE_CALIBRATION_SPC_PROTOCOL;
int main()
{
CORE_CALIBRATION_SPC_PROTOCOL msgInfo = {0};
msgInfo.sMsg.CLB_SPC_Protocol_Version = 64;
return 0;
}
参考资料:
联合体、位段巧妙用法_c语言联合体和位段-CSDN博客