Gui*_*osa 3 c++ file huffman-code
我正在使用霍夫曼算法开发文件压缩器,现在我面临的问题是:
通过使用该算法:stackoverflow,我得到以下结果:
a,c,e,f,k,l,r,s,t,v,w = 1 time repeated
o = 2 times repeated
a,c,e,f,k,l,r,s,t,v,w = 7.69231%
and
o = 15.3846%
Run Code Online (Sandbox Code Playgroud)
所以我开始插入二进制树,这将得到结果:
o=00
a=010
e=0110
c=0111
t=1000
s=1001
w=1010
v=1011
k=1100
f=1101
r=1110
l=1111
Run Code Online (Sandbox Code Playgroud)
这意味着树中角色的路径,考虑0为左,1为右.
然后单词"stackoverflow"将是:100110000100111010011111000010110110111011011111001010
好吧,我想将整个值放入一个二进制文件中,这将导致47位,这将是6字节,但我只能使它成为47字节,因为最小值将被放入一个文件与fwrite或者fprintf是1byte,使用sizeof(某事物).
比我的问题是:我如何只在我的文件中打印一下?
只需将"标题"写入文件:位数,然后将这些位"打包"为填充最后一位的字节.这是一个样本.
#include <stdio.h>
FILE* f;
/* how many bits in current byte */
int bit_counter;
/* current byte */
unsigned char cur_byte;
/* write 1 or 0 bit */
void write_bit(unsigned char bit)
{
if(++bit_counter == 8)
{
fwrite(&cur_byte,1,1,f);
bit_counter = 0;
cur_byte = 0;
}
cur_byte <<= 1;
cur_byte |= bit;
}
int main()
{
f = fopen("test.bits", "w");
cur_byte = 0;
bit_counter = 0;
/* write the number of bits here to decode the bitstream later (47 in your case) */
/* int num = 47; */
/* fwrite(num, 1, 4, f); */
write_bit(1);
write_bit(0);
write_bit(0);
/* etc... - do this in a loop for each encoded character */
/* 100110000100111010011111000010110110111011011111001010 */
if(bit_counter > 0)
{
// pad the last byte with zeroes
cur_byte <<= 8 - bit_counter;
fwrite(&cur_byte, 1, 1, f);
}
fclose(f);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
要做完整的霍夫曼编码器,你必须在开始时写入位代码.