博客首页 注册 建议与交流 排行榜 加入友情链接
推荐 投诉 搜索: 帮助

好好学习

  bilbo.cublog.cn

关于作者
姓名:你知道
职业:IT
年龄:每年大一岁
位置:地球
个性介绍:挺笨
Email: bilbo0214@163.com
|| << >> ||
我的分类


bit-stuffing in C

bit-stuffing在HDLC中有应用,如果不使用HDLC芯片解析,则需要自己来处理。
下面是bit-stuffing的简单实现。
int bit_stuffing(
unsigned char *psrc, /* source buffer */
unsigned short lsrc, /* source buffer length in bytes */
unsigned char *pdest, /* destination buffer */
unsigned short ldest) /* destination buffer length in bytes */
{
unsigned int bytepos = 0;
unsigned int bitpos = 0;

unsigned int i = 0, j = 0;
unsigned int count_one = 0;
unsigned char mask[8] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};

for (i = 0; i < lsrc; i++)
{
for (j = 0; j < 8; j++)
{
if (psrc[i] & mask[j])
{
count_one++;
/* copy current '1' bit */
pdest[bytepos] |= mask[bitpos];
if (count_one == 5)
{
/* move position */
bitpos++;
if (bitpos == 8)
{
bytepos++;
bitpos =
0;
}

/* insert a '0' bit */
pdest[bytepos] &= (~mask[bitpos]);
count_one =
0;
}
}
else
{
count_one =
0;
}

/* move position */
bitpos++;
if (bitpos == 8)
{
bytepos++;
bitpos =
0;
}
}
}

return(0);
}


int bit_destuffing(
unsigned char *psrc, /* source buffer */
unsigned short lsrc, /* source buffer length in bytes */
unsigned char *pdest, /* destination buffer */
unsigned short ldest) /* destination buffer length in bytes */
{
unsigned int bytepos = 0;
unsigned int bitpos = 0;

unsigned int i = 0, j = 0;
unsigned int count_one = 0;
unsigned char mask[8] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};

for (i = 0; i < lsrc; i++)
{
for (j = 0; j < 8; j++)
{
if (psrc[i] & mask[j])
{
count_one++;
/* copy current '1' bit */
pdest[bytepos] |= mask[bitpos];

/* move position */
bitpos++;
if (bitpos == 8)
{
bytepos++;
bitpos =
0;
}

}
else
{
if (count_one == 5) /* remove the '0' bit */
{
}
else
{
/* move position */
bitpos++;
if (bitpos == 8)
{
bytepos++;
bitpos =
0;
}
}
count_one =
0;
}
}
}

return(0);
}

发表于: 2008-07-07,修改于: 2008-07-07 17:37,已浏览255次,有评论0条 推荐 投诉


网友评论
 发表评论