Type-Length-Value 編碼:T、L 長度固定(通常 1-4 字節),V 長度由 L 指定,V 可嵌套子 TLV。示例(大端模式,T=4字節,L=2字節):
T = {0x09, 0x00, 0x00, 0x00} // Tag = 9
L = {0x04, 0x00} // Length = 4
V = {0x01, 0x01, 0x01, 0x01} // Value
typedef struct _stIE {
unsigned int ulTag; // T
unsigned short usLen; // L
unsigned char *pValue; // V
} IE;
typedef struct _stMsg {
IE ie;
struct _stMsg *pNext;
} Msg; // 有序鏈表,按 Tag 遞增
CreateSortMsgList:解析原始字節流,構建按 Tag 排序的鏈表。Sort:將無序 TLV 消息按 Tag 排序輸出。CompareMsg:比較兩條消息,輸出完全相同(T、L、V 均同)的信元個數。IE *GetIEFromMsg(const unsigned char *pInMsg) {
IE *pIE = malloc(sizeof(IE));
pIE->ulTag = *(unsigned int *)pInMsg;
pIE->usLen = *(unsigned short *)(pInMsg + TLV_T_LEN);
pIE->pValue = (unsigned char *)(pInMsg + TLV_T_LEN + TLV_L_LEN);
return pIE;
}
遍歷鏈表找到第一個 Tag 大於新信元的位置插入,保持鏈表有序。
雙重循環遍歷兩個有序鏈表,利用 memcmp 比較 Value 內容。
主函數構造兩條測試消息,驗證排序與比較功能,輸出相同信元數量。