写作比特形式的文件在C文件 [英] Writing files in bit form to a file in C

查看:126
本文介绍了写作比特形式的文件在C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现哈夫曼算法C.我已经得到了基本功能下降高达那里得到二进制codewords点。因此,例如,ABCD将是100011000或类似的东西。现在的问题是怎么写的二进制形式此code在com pressed文件。我的意思是,如果我写的每一个正常1和0将是一个字符,所以没有COM pression。

i am implementing the huffman algorithm in C. i have got the basic functionality down upto the point where the binary codewords are obtained. so for example, abcd will be 100011000 or something similar. now the question is how do you write this code in binary form in the compressed file. i mean if i write it normally each 1 and 0 will be one character so there is no compression.

我需要写的1和0在其位的形式。是可能的C.如果又如何?

i need to write those 1s and 0s in their bit form. is that possible in C. if so how?

推荐答案

直到你有足够的比特来填充一个字节,然后写它收集位。

Collect bits until you have enough bits to fill a byte and then write it..

例如。是这样的:

int current_bit = 0;
unsigned char bit_buffer;

FILE *f;

void WriteBit (int bit)
{
  if (bit)
    bit_buffer |= (1<<current_bit);

  current_bit++;
  if (current_bit == 8)
  {
    fwrite (&bit_buffer, 1, 1, f);
    current_bit = 0;
    bit_buffer = 0;
  }
}

一旦你完成编写位,你必须刷新位缓冲区。这样做只写位,直到current_bit等于零:

Once you're done writing your bits you have to flush the bit-buffer. To do so just write bits until current_bit equals to zero:

void Flush_Bits (void)
{
  while (current_bit) 
    WriteBit (0);
}

这篇关于写作比特形式的文件在C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆