从文件中的特定位开始读取字节-C#

从文件中的特定位开始读取字节-C#,c#,byte,bit-shift,bits,C#,Byte,Bit Shift,Bits,我需要从.bin读取一个字节,但从特定位开始,例如: 如果我有两个字节: 01010111 10101100 程序应该能够读取任何位,比如从第3位(或索引2)开始: 结果应该是01011110 我可以从任何位开始读取字节,除非起始位是字节末尾的位:0101011[1…]//返回不同的内容 我的代码是: byte readByte(int indexInBits, byte[] bytes) { int actualByte = (indexInBits+1)/8;

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

如果我有两个字节:

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

结果应该是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);
    }
byte readByte(int indexInBits,byte[]字节)
{
int实际字节=(indexInBits+1)/8;
int indexInByte=(indexInBits)%8;
int b1=字节[实际字节]>8-索引字节;
返回(字节)(b1+b2);
}
怎么了

谢谢

字节读取字节(整数索引,字节[]字节)
{
int bytePos=指数/8;
int-bitPos=索引%8;
int byte1=字节[bytePos]>8位;
返回(字节)(字节1+字节2);
}

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

请澄清
我可以读取从任何位开始的字节,除非起始位是字节末尾的位
。你的意思是当起始位和结束位相同时它不工作吗?像
1000 0001
?您可以创建一个位数组,将其转换为字符串,然后使用SubString方法?!只需将其转换回…
intactualbyte=(indexInBits+1)/8
为indexInBits==7返回1。但是第7位仍然在第1个字节中,所以actualByte应该是0。减号隐式地位于移位运算符之前。所以括号在“bytes[bytePos+1]>>(8-bitPos);”中是多余的。我还认为索引是基于0的,因为在问题中提到了“让我们假设从第3位(或索引2)开始):”-所以bytePos确实是(索引+1)/8。。或者不是吗?我想如果索引是7,那么7/8等于0(int),但是8/8等于1,这是错误的字节。是的,这确实有效,我不知道为什么我有(索引+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);
    }
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);
}