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; } uint32_t instead of unsigned int. Why don't you accept any digit and reinterpret them as an unsigned value in your function?bool from this function.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)); }
nis non-zero?a == 0, but your code snippet indicates, that you want to check if exactly one bit is set. Can you please specify it?int? How do you want negative values handled?