Writing 'bits' to C++ file streams

bit-manipulation, c#, c++, java, python

Solution

Buffering the individual bits until you've accumulated a whole byte seems like a good idea:

byte b;
int s;

void WriteBit(bool x)
{
    b |= (x ? 1 : 0) << s;
    s++;

    if (s == 8)
    {
        WriteByte(b);
        b = 0;
        s = 0;
    }
}

You just have to deal with the case when the number of bits to be written is not a multiple of eight.

Problem

How can I write 'one bit' into a file stream or file structure each time? Is it possible to write to a queue and then flush it? Is it possible with C# or Java? This was needed when trying to implement an instance of Huffman coding. I can't write bits into files, so write them to a bitset and then (when compression was completed) write 8-bit piece of it each time (exclude last one).

Original source