在数组中设置/取消设置n个连续位

时间:2012-10-11 19:07:38

标签: c

我想找到数组中设置或取消设置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;
 }

1 个答案:

答案 0 :(得分:0)

这就是我提出的:

简单地循环遍历数组并一次检查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;
}