1

我需要从 .bin 中读取一个字节,但从特定位开始,例如:

如果我有这两个字节:

01010111 10101100

该程序应该能够从任何位读取,假设从第 3 位(或索引 2)开始:

01[010111 10]101100

结果应该是 01011110

我可以从任何位开始读取一个字节,除非起始位是字节末尾的那个:0101011[1 ...] //返回不同的东西..

我的代码是:

byte readByte(int indexInBits, byte[] bytes)
    {
        int actualByte = (indexInBits+1)/8;
        int indexInByte = (indexInBits)%8;
        int b1 = bytes[actualByte] << indexInByte;
        int b2 = bytes[actualByte+1] >> 8 - indexInByte;
        return (byte)(b1 + b2);
    }

它有什么问题?

谢谢

4

1 回答 1

0
byte ReadByte(int index, byte[] bytes)
{
    int bytePos = index / 8;
    int bitPos = index % 8;
    int byte1 = bytes[bytePos] << bitPos;
    int byte2 = bytes[bytePos + 1] >> 8 - bitPos;
    return (byte)(byte1 + byte2);
}

我现在无法验证这一点,但这应该可以按预期工作。

于 2013-04-19T13:03:44.293 回答