Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing files in bit form to a file in C

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 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?

like image 727
sfactor Avatar asked Dec 06 '09 20:12

sfactor


People also ask

How do you write a binary file?

To write to a binary fileUse the WriteAllBytes method, supplying the file path and name and the bytes to be written. This example appends the data array CustomerData to the file named CollectedData. dat .

What is the syntax for writing a file in C using binary mode?

Now the fwrite() function is used to write to a binary file, like so: fwrite(&myRecord, sizeof(struct record), 1, ptr);

What is the proper way of opening a file for writing as binary?

To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing.

Which method is used for writing data in binary file?

dump(): The method used for writing data to binary file is dump() method. It takes two arguments 'file object' and 'file' as parameters. It returns the object representation in byte mode.


1 Answers

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);
}
like image 192
Nils Pipenbrinck Avatar answered Oct 12 '22 10:10

Nils Pipenbrinck