0

我想找到n在数组中设置或取消设置连续位的位置。

示例数组:

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;
 }
4

1 回答 1

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;
}
于 2013-10-09T16:34:08.380 回答