I want to test whether any single bit is set in a C int
. I don't care which bit it is.
Equivalent to
if (1 == count_bits (n))
I'm curious if there is a non-looping algorithm for this which does not require special hardware support.
I want to test whether any single bit is set in a C int
. I don't care which bit it is.
Equivalent to
if (1 == count_bits (n))
I'm curious if there is a non-looping algorithm for this which does not require special hardware support.
If only one bit is set, then the number is a power of two.
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;
}
The simplest way is probably to convert to an unsigned type.
Then we are simply testing whether we have an exact power of two.
We can use a simple observation that these are the only non-zero numbers that have no bits in common with n-1
:
bool is_power_of_two(unsigned int n)
{
return n && ! (n & (n-1));
}