You can create an extension method for a stream that enumerates a bit, for example:
public static class StreamExtensions { public static IEnumerable<bool> ReadBits(this Stream input) { if (input == null) throw new ArgumentNullException("input"); if (!input.CanRead) throw new ArgumentException("Cannot read from input", "input"); return ReadBitsCore(input); } private static IEnumerable<bool> ReadBitsCore(Stream input) { int readByte; while((readByte = input.ReadByte()) >= 0) { for(int i = 7; i >= 0; i--) yield return ((readByte >> i) & 1) == 1; } } }
Using this extension method is easy:
foreach(bool bit in stream.ReadBits()) {
Tommy carlier
source share