
I just had the need for code that checks if for a given unsigned int only one bit is set. This is valid for a limited set only (1, 2, 4, 8, 16, etc.)
But what code would you write to determine this? I came up with two totally different solutions, but I was wondering what other programmers would come up with (maybe obvious, way better solutions?). Also wonder what the fastest way is :)
// Listing 1, shift right until a bit falls off
// if it does, the remainder must be 0
bool one_bit_set( unsigned int v ) {
if (!value) return false;
unsigned int o = v;
while (v && v==o) v>>=1;
return !v;
}

// Listing 2, switch
switch (v) {
case 1:
case 2:
case 4:
...
case 2147483648:
return true;
return false;
}

