c++ - 如何在文件中打印位而不是字节?

标签 c++ file huffman-code

我正在使用霍夫曼算法开发文件压缩器,现在我面临的问题是:

通过对词使用算法: 计算器,我得到以下结果:

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/

相关文章:

c++ - 检查2个字符串中是否有公共(public)子字符串c++

linux - trace_ext4_request_inode(dir, mode) 的意义?

huffman-code - 构建规范霍夫曼树的最有效(*)方法是什么?

java - 霍夫曼代码将位写入文件以进行压缩

java - 为什么此代码适用于此 TopCoder 概率?

c++ - 是什么导致十六进制到二进制转换器(C++ 代码)中出现这些奇怪的输出?

c++ - 替代数组表示

c++ - std::copy 上的 vector push_back

Java 插入按钮,将 MySQL 添加到数据库和表

javascript - Jquery 中上传的文件未显示