Given a 32 or 64 bit integer in C++03, what is an efficient way to determine whether there is exactly one bit set or not? (e.g. value is exactly one of 1, 2, 4, 8, 16, 32, etc.) Are there any builtins to C++ 03 library (or if not then C++11) that will work efficiently on whatever hardware I happen to be on? I'd like to use this for a decaying message that occurs ever less frequently on multiple occurrences.
If you have an integer x
that is already known not to be zero, then
if (0 == (x & (x - 1)))
{
there_is_only_1_bit = true;
}