C 在数组中设置/取消设置n个连续位
我想找到数组中设置或取消设置连续位的位置 示例阵列:C 在数组中设置/取消设置n个连续位,c,C,我想找到数组中设置或取消设置连续位的位置 示例阵列: a[0] = 0x0fffffff a[1] = 0x000000f0 a[2] = 0xffffff00 如果我想找到前8个未设置位,它必须返回28(数组中的第28位位置) 如果我想找到前32个未设置位,它必须返回40(数组中的第40位位置) 我正在尝试扩展我发现的代码,以便它能够处理任意大的数组: int BitCount(unsigned int u) { unsigned int uCount;
a[0] = 0x0fffffff
a[1] = 0x000000f0
a[2] = 0xffffff00
如果我想找到前8个未设置位,它必须返回28(数组中的第28位位置)
如果我想找到前32个未设置位,它必须返回40(数组中的第40位位置)
我正在尝试扩展我发现的代码,以便它能够处理任意大的数组:
int BitCount(unsigned int u)
{
unsigned int uCount;
uCount = u
- ((u >> 1) & 033333333333)
- ((u >> 2) & 011111111111);
return
((uCount + (uCount >> 3))
& 030707070707) % 63;
}
这就是我想到的: 只需在数组中循环,并一次检查1位,查看其是否已设置
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;
}
int未设置位(无符号int a[],int-sizeOfArray,int-requiredBits)
{
//一行中找到的位数
int=0;
//数组中的当前索引
int指数=0;
//当前位
int位=0;
而(指数31);
//位未设置
如果(数据==0)
{
发现++;
//找到所需金额,返回起始位置
如果(找到==所需位)
{
返回位+1+(索引*32)-所需位;
}
}
//位已设置,重置找到计数
其他的
{
发现=0;
}
//递增我们正在检查的位
位++;
//递增我们正在检查的数组索引
如果(位>=32)
{
位=0;
索引++;
}
}
//找不到
返回-1;
}
请显示您的代码,并对您认为“不是好方法”的地方进行评论所以人们可以给你有用的答案。@AlexeiLevenkov我能写下一些32位整数的基本代码,但不能扩展到可变大小的数组。因此,来了专家向我们展示你对32位整数的了解,也许我们可以帮助扩展你当前的解决方案这是我对32位//From的了解:'int BitCount(unsigned int u){unsigned int-uCount;uCount=u-((u>>1)&033333333)-(u>>2)&0111111111111);return((uCount+(uCount>>3))&0307070707)%63;}int-First0Bit(int-i){i=~i;return BitCount((i&(-i))-1);}我认为这对于int大小的数据类型(32位)来说非常快。