gpt4 book ai didi

c# - 如何从流中写入/读取位? (C#)

转载 作者:太空狗 更新时间:2023-10-29 20:53:45 24 4
gpt4 key购买 nike

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

最佳答案

您可以在 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;
}
}
}

使用这个扩展方法很简单:

foreach(bool bit in stream.ReadBits())
{
// do something with the bit
}

注意:您不应该在同一个 Stream 上多次调用 ReadBits,否则后续调用会忘记当前位的位置而直接开始读取下一个字节。

关于c# - 如何从流中写入/读取位? (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1315839/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com