This is a fraction of the binary writer I'm writing, and I'm trying find some way to improve it.
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;
}
}
byte
so you should work at that level at a minimum. You won't gain much in terms of efficiency and maintainability, in fact, it's quite the opposite. You're making it harder on yourself unnecessarily. Besides, that's why there's theBitArray
type. \$\endgroup\$