views:

136

answers:

1

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.

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

+8  A: 

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

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

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);
}
Nils Pipenbrinck
thanks for pointing this out...so how to end the file then?...i presume we need to do this ourselves in this case.
sfactor
just call Flush_Bits as defined above.
Nils Pipenbrinck