c# - 从流中读取一定数量的位的问题
问题描述
我有读取大小从 1 到 8 的位块的代码。 Homewer,它不能正常工作。
private byte BitRead = 8;
private ushort ValRead = 0;
private byte[] And = new byte[] { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF };
private byte[] IAnd = new byte[] { 0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00 };
public byte ReadBit(byte Bits)
{
Bit = 0;
if (BitRead > 7)
{
BitRead -= 8;
Bit = 0;
ValRead = (ushort)((ValRead << 8) | (byte)stream.ReadByte());
}
Bit = (byte)((ValRead >> (8 - BitRead - Bits)) & And[Bits]);
BitRead += Bits;
return Bit;
}
例如本节有 16 个 3 位值:00 04 01 09 C4 D8
在正常情况下会是这样:从我的代码中:
0, 0, 0, 0, 2, 0, 0, 1, 0, 2, 3, 4, 2, 3, 3, 0
0, 0, 0, 0, 2, 0, 0, 1, 0, 2, 0, 4, 2, 0, 3, 0
16 个 5 位值也是如此:84 1F 07 BD EE 73 9E F7 39 CE
正常情况:我的代码:
16, 16, 15, 16, 15, 15, 15, 14, 14, 14, 15, 15, 14, 14, 14, 14
16, 0, 15, 0, 0, 15, 0, 14, 14, 0, 15, 0, 0, 14, 0, 14
解决方案
最后我做到了。感谢PMF指出我的问题。
private byte Bit = 0;
private byte BitRead = 0;
private long ValRead = 0;
private readonly byte[] And = new byte[] { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF };
public byte ReadBit(byte Bits)
{
if (8 - BitRead - Bits < 0)
{
BitRead = (byte)-(8 - BitRead - Bits);
ValRead = (ushort)((ValRead << 8) | (byte)stream.ReadByte());
Bit = (byte)((ValRead >> 8 - BitRead) & And[Bits]);
}
else
{
Bit = (byte)((ValRead >> (8 - BitRead - Bits)) & And[Bits]);
BitRead += Bits;
}
return Bit;
}
推荐阅读
- angular - Angular 4 build --prod bundle 有错误
- javascript - 试图在字符串中获取 javascript 对象
- splunk - 如何破坏同一行中的两个 Splunk 日志?
- php - wordpress 自定义错误页面或在出现错误时重定向到自定义页面
- firebase - 如何从 Firebase Auth 调用 fetchSignInMethodsForEmail()
- ms-access - MS Access - Docmd.OpenReport
- hive - 如何将数据从 kafka 发送到 hive
- python - Remove white margins in a running figure
- c# - C# 双线性插值 RGB
- c++ - lambda 对象构建成本高吗?