如何从/向流写入/读取位?(C#)

Alo*_*kin 6 c#

如何将位写入流(System.IO.Stream)或读入C#?谢谢.

Tom*_*ier 13

您可以在Stream上创建一个枚举位的扩展方法,如下所示:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用此扩展方法很简单:

foreach(bool bit in stream.ReadBits())
{
    // do something with the bit
}
Run Code Online (Sandbox Code Playgroud)