#include "stdafx.h" #include "stdio.h" #include "stdlib.h" #include #include "util_hdlc.h" #define __HDLC_FLAG 0x7E #define __HDLC_ESC 0x7D #define __HDLC_COMPL 0x20 void log0(const char* ss) { FILE* fp; fp = fopen("log.txt", "ab"); fwrite(ss, 1, strlen(ss), fp); fwrite("\r\n", 1, 2, fp); fclose(fp); } void log_hex(char* msg, char* buf, int size) { char text[4096]; char tmp[10]; int i; sprintf(text, "%s - ", msg); for(i = 0; i < size; ++i) { sprintf(tmp, "%02X ", buf[i]); strcat(text, tmp); } strcat(text, "\r\n"); log0(text); } void hdlc_encode(unsigned char* buf, int size, unsigned char* out_buf, int* out_size) { int inx = 0; int i; out_buf[inx++] = __HDLC_FLAG; // start flag for(i = 0; i < size; ++i) { if(buf[i] == __HDLC_ESC || buf[i] == __HDLC_FLAG) { // if esc? out_buf[inx++] = __HDLC_ESC; out_buf[inx++] = (unsigned char)(buf[i] ^ __HDLC_COMPL); } else { out_buf[inx++] = buf[i]; } } out_buf[inx++] = __HDLC_FLAG; // flag *out_size = inx; } int hdlc_decode(unsigned char* buf, int size, unsigned char* out_buf, int* out_size) { int inx = 0; int i; // size if(size < 3) { return 0; } // start if(buf[0] != __HDLC_FLAG) { return 0; } // decode for(i = 1; i < size-1; ++i) { if(buf[i] == __HDLC_ESC) { ++i; out_buf[inx++] = (unsigned char)(buf[i] ^ __HDLC_COMPL); } else { out_buf[inx++] = buf[i]; } } // end if(buf[size-1] != __HDLC_FLAG) return 0; *out_size = inx; return 1; }