数据通讯拆分包算法
在設備的通訊過程中,可能存在數據很長,導致數據無法一次性發送,或者長數據發送會丟失,為了解決這一問題,自己用C語言實現的一個簡單的拆分包算法:
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include<stdlib.h>
#define ?dataTotalLen ?100
#define ?groupLen ? ? ?7//拆分后一個數據包的長度
int main(void)
{
? ? uint8_t buf[dataTotalLen];
? ? uint16_t tt = 0;
? ? uint8_t div_dataPackSegLen,rem_dataPackSegLen;
? ? uint16_t datalen = sizeof(buf);
? ? printf("datalen = %d\r\n",datalen);
? ? for( tt = 1;tt <= datalen;tt++)//假設一個數據包有這么多的數據,根據datalen來判斷
? ? {
? ? ? ?buf[tt-1] = tt;//填充數據
? ? }
? ? div_dataPackSegLen = datalen / groupLen;//數據包可以分為幾個包上傳
?? ?rem_dataPackSegLen = datalen % groupLen;//多余的數據與最后一個數據包合并再上傳
? ? printf("可以分成%d個數據包,最后一個數據包附加%d個數據一起上傳!!!\r\n",div_dataPackSegLen,rem_dataPackSegLen);
? ? for(tt = 0;tt < datalen - rem_dataPackSegLen;tt += groupLen)//對數據包進行
? ? {
? ? ? ? printf("tt=%d\r\n",tt);
? ? ? ? if(tt == (div_dataPackSegLen * groupLen - groupLen))//數據包合并
? ? ? ? {
? ? ? ? ? ? for(uint8_t i = tt;i < tt + groupLen + rem_dataPackSegLen;i++)//拆包
? ? ? ? ? ? {
? ? ? ? ? ? ? ?printf("buf[%d]=%d \r\n",i,buf[i]);
? ? ? ? ? ? }
? ? ? ? }else{
? ? ? ? ? ? for(uint8_t i = tt;i < tt+groupLen;i++)//拆包
? ? ? ? ? ? {
? ? ? ? ? ? ? ?printf("buf[%d]=%d \r\n",i,buf[i]);
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? return 0;
}
?
總結
- 上一篇: C#串口上位机软件--IOT串口调试精灵
- 下一篇: 单片机编程之联合体(union)的妙用