采用 0x7e 表示,若校验码、消息头以及消息体中出现 0x7e,则要进行转义处理,转义
规则定义如下:
0x7e <————> 0x7d 后紧跟一个 0x02;
0x7d <————> 0x7d 后紧跟一个 0x01。
转义处理过程如下:
发送消息时:消息封装——>计算并填充校验码——>转义;
接收消息时:转义还原——>验证校验码——>解析消息。
示例:
发送一包内容为 0x30 0x7e 0x08 0x7d 0x55 的数据包,则经过封装如下:0x7e 0x30 7d 0x02 0x08 0x7d
0x01 0x55 0x7e。
以下记录转义处理的算法实现:VC6工程试验环境
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
unsigned int GPS_SEND_NUM=49;
unsigned char Mac_Id[6]={0x01,0x60,0x20,0x76,0x84,0x41};
unsigned char GPS_Info[60]={0x7e,
02,00,00,0x22,
0x01,0x60,0x20,0x76,0x84,0x41,
00,0x7c,
00,00,00,00,
00,00,00,01,
0x01,0xd9,0x95,0x7e,
0x07,0x38,0xe3,0x7d,
00,00,
00,00,
00,00,
0x19,
02,
0x25,
0x08,
0x08,
0x56,
00,00,00,00,00,00,
0xe7,
0x7e
};
void GPS_Encode()//默认GPS 49字节[0-48]
{
unsigned char result=0x00;
result=GPS_Info[1];
for(int i=2;i<=46;i++)
{
result^=GPS_Info[i];
}
GPS_Info[47]=result;
GPS_SEND_NUM=49;
for(int m=11;m<47;m++)//′ó[11-47]
{
if(GPS_Info[m]==0x7d)
{
for(int n=GPS_SEND_NUM;n>m+1;n--)
{
GPS_Info[n]=GPS_Info[n-1];
}
GPS_Info[m+1]=0x01;
GPS_SEND_NUM+=1;
}
}
for(int k=11;k<47;k++)
{
if(GPS_Info[k]==0x7e)
{
for(int s=GPS_SEND_NUM;s>k+1;s--)
{
GPS_Info[s]=GPS_Info[s-1];
}
GPS_Info[k]=0x7d;
GPS_Info[k+1]=0x02;
GPS_SEND_NUM+=1;
}
}
}
int main(int argc, char* argv[])
{
//算法实现
GPS_Encode();
//打印输出
for(int s=0;s<60;s++)
{
printf("%02x",GPS_Info[s]);
}
printf("\r\n");printf("\r\n");printf("\r\n");
return 0;
}