帮我找一个C语言的HDLC代码
时间: 2023-03-19 07:22:59 浏览: 111
HDLC的源代码
5星 · 资源好评率100%
下面是一个简单的C语言HDLC协议的实现,其中使用了CRC-16校验:
```
#include <stdio.h>
#include <string.h>
#define FLAG 0x7E
#define ESC 0x7D
#define XON 0x11
#define XOFF 0x13
#define CRC16_POLY 0x8005
typedef unsigned char BYTE;
typedef unsigned short WORD;
WORD crc16(BYTE *data, int len)
{
WORD crc = 0xFFFF;
int i, j;
for (i = 0; i < len; i++) {
crc ^= (WORD)data[i] << 8;
for (j = 0; j < 8; j++) {
if (crc & 0x8000)
crc = (crc << 1) ^ CRC16_POLY;
else
crc <<= 1;
}
}
return crc;
}
void hdlc_encode(BYTE *input, int input_len, BYTE *output, int *output_len)
{
int i, j, k;
WORD crc = crc16(input, input_len);
output[0] = FLAG;
for (i = 0, j = 1; i < input_len; i++) {
if (input[i] == FLAG || input[i] == ESC) {
output[j++] = ESC;
output[j++] = input[i] ^ 0x20;
} else {
output[j++] = input[i];
}
}
for (k = 0; k < 2; k++) {
if (crc & 0x8000)
output[j++] = ESC;
output[j++] = (BYTE)(crc >> 8) ^ 0x20;
crc <<= 8;
}
output[j++] = FLAG;
*output_len = j;
}
void hdlc_decode(BYTE *input, int input_len, BYTE *output, int *output_len)
{
int i, j;
WORD crc = 0xFFFF;
for (i = 1, j = 0; i < input_len - 1; i++) {
if (input[i] == ESC) {
output[j++] = input[++i] ^ 0x20;
} else {
output[j++] = input[i];
}
}
*output_len = j - 2;
crc = crc16(output, *output_len);
if ((BYTE)(crc >> 8) == input[input_len - 3] ^ 0x20 && (BYTE)crc == input[input_len - 2] ^ 0x20) {
*output_len -= 2;
} else {
*output_len = -1;
}
}
int main()
{
BYTE input[] = {0x01, 0x02, 0x03, 0x04};
BYTE output[1024];
int output_len;
hdlc_encode(input, sizeof(input), output, &output_len);
printf("Encoded: ");
for (int i = 0; i < output_len; i++) {
printf("%02X ", output[i]);
}
printf("\n");
BYTE decoded[1024];
int decoded_len;
hdlc_decode(output, output_len, decoded, &decoded_len);
printf("Decoded: ");
for (int i = 0; i < decoded_len; i++) {
printf("%02X ", decoded[i]);
}
printf("\n");
return 0;
阅读全文