Bitstream of variable-length Huffman codes - How to write to file?

后端 未结 2 1621
小鲜肉
小鲜肉 2021-01-22 13:02

I\'m working on a Huffman coding/decoding project in C and have a good understanding of how the algorithm should store information about the Huffman tree, re-build the tree duri

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-22 13:36

    Here's some pseudo-code to give you the general idea:

    static byte BitBuffer = 0;
    static byte BitsinBuffer = 0;
    
    static void WriteBitCharToOutput(char bitChar);
    // buffer one binary digit ('1' or '0')
    {
      if (BitsInBuffer > 7)
      {
        stream.write(BitBuffer);
        BitsInBuffer = 0;
        BitBuffer = 0; // just to be tidy
      }
    
      BitBuffer = (BitBuffer << 1) | (bitChar == '1' ? 1 : 0);
      BitsInBuffer++;
    }
    
    static void FlushBitBuffer()
    // call after last character has been encoded
    // to flush out remaining bits
    {
      if (BitsInBuffer > 0)
      do
      {
        WriteBitCharToOutput('0'); // pad with zeroes
      } while (BitsInBuffer != 1);
    }
    

提交回复
热议问题