是否有一个技巧可以测试是否在int的任何地方设置了非特定位?

时间:2018-10-29 10:16:13

标签: c bit-manipulation bit

我想测试C int中是否设置了任何单个位。我不在乎它是哪一位。

等同于

if (1 == count_bits (n))

我很好奇是否有一种不需要特殊硬件支持的非循环算法。

2 个答案:

答案 0 :(得分:5)

如果仅设置一位,则该数字为2的幂。

unsigned int IsPowerOfTwoNoLoop(unsigned int input)
{
    unsigned int temp = input;
    if(0 == input)
    {
      return 0;
    }
    temp -= 1;
    /*Example of the logic:*/
    /*  0100 (4 DEC) - 1 = 0011
        0011 & 0100 = 0000 
    */
    if (temp & input) /* if not zero - not pow of two */
    {
        printf("%u Is NOT the power of two !\n", input);
        return 0;
    }

    printf("%u Is the power of two !\n", input);
    return 1;
}

答案 1 :(得分:1)

最简单的方法可能是转换为无符号类型。

然后,我们只是在测试是否具有2的精确乘方。

我们可以简单地观察到,这是唯一与n-1没有相同位的非零数字:

bool is_power_of_two(unsigned int n)
{
    return n && ! (n & (n-1));
}