1、一條消息由一個或多個基本信息單元(Information Element)IE組成。
2、每個IE採用TLV編碼。TLV是Tag Length Value的縮寫,它是一種變長數據的編解碼, 由Tag,Length(value的長度)及Value三個域組成。
3、Tag固定佔4個字節,Length固定佔2個字節。
4、字節序按照大端序處理。
根據IE的Tag值大小對消息中所有的IE由小到大排序,並輸出。
例如消息:0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x66
前面4個字節是tag:0x00, 0x00, 0x00, 0x00
後面2個字節是長度:0x00, 0x02,
後面的2個字節0x00, 0x66是Value 該消息只有一個IE。
運行時間限制: 無限制
內存限制: 無限制
輸入:
字節流,字節之間用“,”隔開,
輸出:
根據IE的Tag值的大小對消息中所有的IE排序,並輸出。
字節序按照大端序處理。 字節流,字節之間用“,”隔開,
如果消息解碼失敗,請輸出false。
樣例輸出: 0x00, 0x00, 0x00, 0x66, 0x00, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00
思路:
略過前面的位,直接去計算第22,23,27,28位的值,就知道有n個Value,然後讀取後續n個就行了,具體思路已經註釋。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXBUF 65535
char buf[MAXBUF];
char IEs[100][MAXBUF];
char temp[MAXBUF];
int main(){
while(gets(buf)){
int flag=0;
int line=strlen(buf);//數據長度
int handledLen=0;//統計已經處理過多少數據
char *ptr=buf;
int counter=0;//統計有多少個ie
int i,j;
for(i=0;i<100;++i){
if(handledLen>=line)//到達末尾,結束
break;
int ieValueNum=(ptr[22]-'0')*16*16*16 + \
(ptr[23]-'0')*16*16 + (ptr[27]-'0')*16 +(ptr[28]-'0');//計算ie的value域的個數
int ieLen=29+5*ieValueNum;//求出整個編碼ie長度
if(line-handledLen<ieLen){
printf("false\n");
flag=1;
break;
}
//將該ie複製到數組中
strncpy(IEs[i],ptr,ieLen);
IEs[i][ieLen]='\0';
//更新信息
ptr=ptr+ieLen+1;
handledLen+=ieLen+1;
++counter;
}
if(flag==1)
continue;
for(i=0;i<counter-1;++i)
for(j=i;j<counter;++j){
if(strcmp(IEs[i],IEs[j])>0){
strcpy(temp,IEs[i]);
strcpy(IEs[i],IEs[j]);
strcpy(IEs[j],temp);
}
}
printf("%s",IEs[0]);
for(j=1;j<counter;++j){
printf(",") ;
printf("%s",IEs[j]);
}
printf("\n");
}
return 0;
}
/*
0x00,0x00,0x00,0x66,0x00,0x02,0x01,0x02,0x00,0x00,0x00,0x77,0x00,0x00,0x00,0x00,0x00,0x55,0x00,0x01,0xfa,0x00,0x00,0x00,0x45,0x00,0x03,0xff,0xfe,0xfd
*/