我想要找到在数组中设置或取消设置n连续位的位置。
数组示例:
a[0] = 0x0fffffff
a[1] = 0x000000f0
a[2] = 0xffffff00如果我想查找前8个未设置的位,它必须返回28 (数组中的第28位)
如果我想找到前32个未设置的位,它必须返回40 (数组中的第40位位置)
我正在尝试扩展我找到的here代码,以便它可以与任意大的数组一起工作:
int BitCount(unsigned int u)
{
unsigned int uCount;
uCount = u
- ((u >> 1) & 033333333333)
- ((u >> 2) & 011111111111);
return
((uCount + (uCount >> 3))
& 030707070707) % 63;
}发布于 2013-10-10 00:34:08
这是我想出来的:
简单地循环数组,一次检查一位,看看是否设置了它。
int UnsetBits(unsigned int a[], int sizeOfArray, int requiredBits)
{
//number of found bits in a row
int found = 0;
//current index in array
int index = 0;
//current bit
int bit = 0;
while(index < sizeOfArray)
{
//isolate the current bit
int data = ((a[index] << (31 - bit)) >> 31);
//bit is unset
if(data == 0)
{
found++;
//found required amount, return start position
if(found == requiredBits)
{
return bit + 1 + (index * 32) - requiredBits;
}
}
//bit is set, reset found count
else
{
found = 0;
}
//increment which bit we are checking
bit++;
//increment which array index we are checking
if(bit >= 32)
{
bit = 0;
index++;
}
}
//not found
return -1;
}https://stackoverflow.com/questions/12846789
复制相似问题