在c/c++中,如何做到huffman编码的比特输入/输出?

asunafy 2010-12-23 03:39:12
我用huffman编码后,文件输出的xx.txt的大小反而比原文件的要大,究其原因是应为用了字符输出;
但我不会比特串输出。曾经找了c语言中流式文件操作,然后用二进制模式打开,用了fwrite()函数,但貌似还是以字符输出的。
请教高人。

...全文
130 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
darkofday 2010-12-23
  • 打赏
  • 举报
回复
不知道回答得正不正确,直接操作二进制位的话,可以用bitset,保存时,除了模式外,应该将其转换为unsigned char,对文件流以bit方式操作我也找了好长时间,好像不能,只能是间接通过char来操作。如果有更好的办法,望指教。
hastings 2010-12-23
  • 打赏
  • 举报
回复
// set the bit at position pos in the array bits to the value state
void set_bit(unsigned char* bits, unsigned int pos, unsigned int state)
{
unsigned char mask = 0x80; // = 128 dec = 10000000 bin
unsigned int j = pos % 8, k = pos / 8;
if(j)
mask >>= j; // shift bitmask to right

if (state)
bits[k] |= mask;
else
bits[k] &= (~mask);
}

// get the state of the bit at position pos in the array bits
unsigned int get_bit(const unsigned char* bits, unsigned int pos)
{
unsigned char mask = 0x80; // = 128 dec = 10000000 bin
unsigned int j = pos % 8;
if(j)
mask >>= j; // shift bitmask to right

return ((mask & bits[pos/8]) ? 1 : 0);
}
witlym311 2010-12-23
  • 打赏
  • 举报
回复
说明你输出的是字符01而不是二进制流,注意写文件的函数的参数设置。
luciferisnotsatan 2010-12-23
  • 打赏
  • 举报
回复
是用一个字符(8bit)记一个0或1的话。转换下,然后再用二进制输出

void cnvtbit(char *in, char *out, size_t len)
{
int i,j;
for(i=0;i<len;i+=8)
for(j=0;j<=7;j++)
{
if(i+j<len)
{
out[i/8] |= (in[i+j]<<(7-j));
}
else
{
break;
}
}
}


使用
	char in[18] = {1,0,0,1, 1,1,0,0, 1,1,0,1, 1,0,1,1, 0,1};
char out[3] = {0};

cnvtbit(in,out,18);
luciferisnotsatan 2010-12-23
  • 打赏
  • 举报
回复
编码后的01你是只存一个比特还是存了一个字节?
jackyjkchen 2010-12-23
  • 打赏
  • 举报
回复
计算机使用huffman编码要搞清楚码元单位,应该以字节为单位进行统计
zhengjiankang 2010-12-23
  • 打赏
  • 举报
回复
fopen(...."wb"(open mode 这里用这个))

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧