国产久操视频-国产久草视频-国产久热精品-国产久热香蕉在线观看-青青青青娱乐-青青青青在线成人视99

聯(lián)合體和結(jié)構(gòu)體一起解析數(shù)據(jù)

01/27 10:50
731
加入交流群
掃碼加入
獲取工程師必備禮包
參與熱點資訊討論

聯(lián)合體是一種數(shù)據(jù)結(jié)構(gòu),其內(nèi)部的成員共享同一塊內(nèi)存。應用這種方式可以簡化多種復雜數(shù)據(jù)的處理。

比如接收一段16進制到的數(shù)據(jù),根據(jù)幀頭不同數(shù)據(jù)的含義不同需要進行解析;第一個字節(jié)為0x01時,后兩個字節(jié)代表一個含義;第一個字節(jié)為0x02時,后四個字節(jié)代表另一個含義;第一個字節(jié)為0x03時,后3個字節(jié)代表另一個含義。首先定義幾個結(jié)構(gòu)體。

struct test_data1
{
uint8_t header;
uint16_t data_xxx;
...
}__attribute__ ((__packed__));
struct test_data2
{
uint8_t header;
uint32_t data_xxx;
...
}__attribute__ ((__packed__));
struct test_data3
{
uint32_t header:8;
uint32_t data_xxx:24;
...
}__attribute__ ((__packed__));

typedef union


{

uint8_t data_bytes[100];

struct test_data1 analysis_data1;

struct test_data2 analysis_data2;

} data;

使用__attribute__ ((__packed__))使字節(jié)不對齊,使用位域來表示三個字節(jié),__attribute__ ((__packed__))和結(jié)構(gòu)體位域可以參考:

結(jié)構(gòu)體位域和__attribute__ ((__packed__))一起用

根據(jù)數(shù)據(jù)值直接使用結(jié)構(gòu)體賦值

memcpy(data.data_bytes, receive, 100);

if(data.data_bytes[0] == 0x01)

{

xxx = data.analysis_data1.data_xxx

}

else if(data.data_bytes[0] == 0x02)

{

xxx = data.analysis_data2.data_xxx

}
else if(data.data_bytes[0] == 0x03)
{
xxx = data.analysis_data3.data_xxx
}

這樣使用聯(lián)合體方便簡化數(shù)據(jù)解析。

相關推薦

长宁县| 化德县| 麻城市| 榕江县| 韶山市| 定边县| 宜兴市| 嘉祥县| 财经| 仙游县| 江陵县| 平果县| 台江县| 天长市| 岳阳县| 乌兰浩特市| 鹤壁市| 江阴市| 昆山市| 洛隆县| 洛南县| 阜南县| 定襄县| 邵阳县| 汤原县| 芜湖市| 太谷县| 舞钢市| 阿鲁科尔沁旗| 湖口县| 确山县| 英超| 内江市| 拉萨市| 涡阳县| 乐安县| 松溪县| 洛隆县| 昌吉市| 简阳市| 临汾市|