spr*_*aff -3 c bit-manipulation bit
我想测试是否在C中设置了任何单个位int.我不在乎它是什么位.
相当于
if (1 == count_bits (n))
Run Code Online (Sandbox Code Playgroud)
我很好奇是否有一个非循环算法,不需要特殊的硬件支持.
如果仅设置一个位,则该数字是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;
}
Run Code Online (Sandbox Code Playgroud)