How to write / read bits from / to a stream? (FROM#)

How can I write bits to a stream (System.IO.Stream) or read in C #? thanks.

+6
c #
source share
2 answers

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()) { // do something with the bit } 
+11
source share

This is not possible for the default stream class. The C # Stream class (BCL) works with byte granularity at its lower level. What you can do is write a wrapper class that reads bytes and breaks them into bits.

For example:

 class BitStream : IDisposable { private Stream m__stream; private byte? m_current; private int m_index; public byte ReadNextBit() { if ( !m_current.HasValue ) { m_current = ReadNextByte(); m_index = 0; } var value = (m_byte.Value >> m_index) & 0x1; m_index++; if (m_index == 8) { m_current = null; } return value; } private byte ReadNextByte() { ... } // Dispose implementation omitted } 

Note. It will read bits from right to left, which may or may not be what you intend.

+3
source share

All Articles