joriszwart.nl

I code dreams™

BitWriter.cs

View Download

public class BitWriter(Stream stream)
{
    private uint _buffer;
    private int _count;

    // write `code` with a number of `bits` (Most Significant Bit)
    public void WriteBits(uint code, int bits)
    {
        for (var i = bits - 1; i >= 0; i--)
        {
            var mask = code >> i;
            var bit = mask & 1;
            _buffer |= bit << _count;
            _count++;

            // flush buffer
            while (_count >= 8)
            {
                stream.WriteByte((byte)(_buffer & 0xFF));
                _buffer >>= 8;
                _count -= 8;
            }
        }
    }

    public void Flush()
    {
        if (_count <= 0)
        {
            return;
        }

        stream.WriteByte((byte)_buffer);
    }
}

View Download