Writing files in bit form to a file in C

后端 未结 1 2053
傲寒
傲寒 2021-02-14 01:20

I am implementing the huffman algorithm in C. I have got the basic functionality down up to the point where the binary codewords are obtained. so for example, abcd will be 10001

1条回答
  •  借酒劲吻你
    2021-02-14 02:21

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

    E.g. something like this:

    int current_bit = 0;
    unsigned char bit_buffer;
    
    FILE *f;
    
    void WriteBit (int bit)
    {
      if (bit)
        bit_buffer |= (1<

    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);
    }
    

    0 讨论(0)
提交回复
热议问题