【问题标题】:getting n consecutive bits set/unset in a array在数组中设置/取消设置 n 个连续位
【发布时间】:2012-10-11 19:07:37
【问题描述】:

我想找到 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;
 }

【问题讨论】:

  • 请展示您的代码并评论您认为它“不是一个好方法”的地方,以便人们可以为您提供有用的答案。
  • @AlexeiLevenkov 我能够为 32 位整数编写一些基本代码,但无法扩展到可变大小的数组。因此来到专家那里
  • 向我们展示您对 32 位整数的了解,也许我们可以帮助您扩展当前的解决方案
  • 这是 32 位的 // 来自:tekpool.wordpress.com/category/bit-count ' int BitCount(unsigned int u) { unsigned int uCount; uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);返回 ((uCount + (uCount >> 3)) & 030707070707) % 63; } int First0Bit(int i) { i=~i;返回位计数((i&(-i))-1); } ' 我认为这对于 int 大小的数据类型(32 位)来说非常快。

标签: c


【解决方案1】:

这是我想出的:

只需遍历数组并一次检查 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;
}

【讨论】:

    猜你喜欢
    • 2021-04-25
    • 2015-10-14
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多