从文件中的特定位开始读取一个字节-C#
本文关键字:一个 -C# 字节 读取 文件 开始 定位 | 更新日期: 2023-09-27 18:10:05
我需要从.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);
}
它怎么了?
感谢
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);
}
我现在无法验证这一点,但这应该如预期的那样有效。