如何检查与预期数字相比,1位是否关闭
本文关键字:1位 是否 数字 何检查 检查 | 更新日期: 2023-09-27 18:14:55
我正在检查FAT系统表,需要确定32位整数与预期值相比是否偏离了一位。通常,列出的位置是当前位置的+1,除非由于另一个文件妨碍而需要跳转。如果磁盘有损坏问题,该值通常会偏离标准设置1位。我已经写了我现在是如何检查的,但想知道是否有一个更简单或快速的方式来执行这个功能。
internal bool CheckFatValueToIndex(int expectedCluster, int recievedValue)
{
/*Clear one bit and compare to expected value
*Return true if expected cluster is 1 bit off*/
if ((expectedCluster | 0x01) == recievedValue || (expectedCluster | 0x02) == recievedValue || (expectedCluster | 0x04) == recievedValue || (expectedCluster | 0x08) == recievedValue || (expectedCluster | 0x10) == recievedValue || (expectedCluster | 0x20) == recievedValue || (expectedCluster | 0x40) == recievedValue || (expectedCluster | 0x80) == recievedValue || (expectedCluster | 0x100) == recievedValue)
return true;
if ((expectedCluster | 0x200) == recievedValue || (expectedCluster | 0x400) == recievedValue || (expectedCluster | 0x800) == recievedValue || (expectedCluster | 0x1000) == recievedValue || (expectedCluster | 0x2000) == recievedValue || (expectedCluster | 0x4000) == recievedValue || (expectedCluster | 0x8000) == recievedValue)
return true;
return false;
}
首先,您需要提取更改的位,这可以通过XOR简单地完成:
expectedCluster ^ receivedValue
每个集合位表示一个差值:如果位相同(0或1),结果为0,如果不相同则为1。
现在你要数它们。你可以使用汉明算法:
int CountSetBits(int x) {
int count = 0;
for (count = 0; x > 0; ++count)
x &= x - 1;
return count;
}
你可以检查它:
return CountSetBits(expectedCluster ^ receivedValue) > 1;
编辑:Quantic建议检查xor数字是否为2的幂,如果您不需要计算有多少损坏的/更改的位,那么这应该更快(如果您关心):
bool IsPowerOf2(int x) {
return x != 0 && (x & (x - 1)) == 0;
}