This is ana fraction of the binary writer I'm writing, and I'm trying find some way to improve it, in any possible way.
using System;
using System.Collections.Generic;
public class ByteBuffer
{
// List used to hold all bytes that will be read
private List<byte> buffer = new List<byte>(32);
private int bitIndex = 0;
/// <summary>
/// Writes an n bits byte onto the buffer.
/// </summary>
public void Write(byte source, int n)
{
if ((n + bitIndex) / 8 > buffer.Count)
{
buffer.AddRange(new byte[(n + bitIndex) / 8 - buffer.Count]);
}
for (int i = 0; i < n; i++)
{
buffer[(bitIndex + i) / 8] |= (byte)(((source >> (n - 1 - i)) & 1) << (int)(7 - (bitIndex + i) % 8));
}
bitIndex += n;
}
}
Thanks.