我正在使用霍夫曼算法开发文件压缩器,现在我面临的问题是:
通过对词使用算法: 计算器,我得到以下结果:
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%
所以我开始将 then 插入到二叉树中,这将得到结果:
o=00
a=010
e=0110
c=0111
t=1000
s=1001
w=1010
v=1011
k=1100
f=1101
r=1110
l=1111
表示字符在树中的路径,0为左,1为右。
那么“stackoverflow”这个词将是: 100110000100111010011111000010110110111011011111001010
好吧,我想将整个值放入一个二进制文件中,以位为单位,这将导致 47 位,这恰好是 6 字节,但我只能将其设为 47 字节,因为将最小值放入使用 fwrite 或 fprintf 的文件是 1byte,通过使用 sizeof(something)。
我的问题是:如何在我的文件中只打印一位?
最佳答案
只需将“ header ”写入文件:位数,然后将这些位“打包”为填充最后一位的字节。这是一个示例。
#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;
}
当然,要实现完整的霍夫曼编码器,您必须在开头编写位代码。
关于c++ - 如何在文件中打印位而不是字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11253123/