Interesting tangent to this question - I think I know a sort of clever answer to the question "How many bits are set in this value"
#include <stdint.h>
#include <stdio.h>
uint8_t NumBitsSet(uint32_t value){
uint8_t num_bits_set = 0;
while(value != 0){
value = value & (value-1);
num_bits_set++;
}
return num_bits_set;
}
int main(int argc, char *argv[]){
uint32_t value = 2147483648;
printf("numbits set in %x = %d", value, NumBitsSet(value));
return 0;
}
You can use this as a basis for determining if exactly one bit is set, though you have to make a special check for zero.
uint8_t exactly_one_bit_set = (value & (value-1)) == 0 ? 1 : 0;
The trick here is that if a value has one bit set then one less than that value will have all the bits below that bit set and that bit cleared. and-ing those two things together will be always be zero.