通常遇到,0xFE 0xFF 则转换为0xFE + 0x00 和 0xFE + 0x01。
Talk is cheap, show me the code.
#include <stdio.h> #include <assert.h> #include <string.h> typedef unsigned char uint8_t; /*set escape char*/ static void escape_character_process(uint8_t *from, int flen, uint8_t *to, int *olen) { int i; int s; uint8_t escape_ff[2] = {0xFE,0x01}; uint8_t escape_fe[2] = {0xFE,0x00}; for(i = 0; i < olen; i++){ for(i = 0; i < olen; i++){ /*assert*/ assert(from); for (i = 0, s = 0; i < flen; i++, s++){ if (from[i] == 0xFF){ memcpy(to+s,escape_ff,2); s += 1; } else if (from[i] == 0xFE){ memcpy(to+s,escape_fe,2); s += 1; } else to[s] = from[i]; } *olen = s; /*total length*/ } int main(void) { uint8_t from[4] = {0x01,0xFE,0xFF,0x02}; uint8_t to[8] = {}; int i; int olen = 0; escape_character_process(from, 4, to, &olen); for(i = 0; i < olen; i++) if (i == olen -1) printf("%02x\n",to[i]); else printf("%02x ",to[i]); return 0; }
原本数据:
0x01,0xFE,0xFF,0x02
0x01,0xFE,0xFF,0x02
运行结果:
01 fe 00 fe 01 02