I know I am massively late to the party, but I just came across this question and I wanted to share my template solution for getting the highest bit that is set in the argument as a value and not the exponent, i.e. not the number 4 but the value 2^4 = 16 if bit 4 is the highest bit that is set. This function can be used for any numeric type:
template<typename T> T top_bit(T n) { T ret; do { ret = n; n &= n - 1; } while (n); return ret; }
It works by remembering the last value and eliminating the lowest bit until no bit is left. Thus, the last value is the one with the highest bit set. An argument of zero will return 0.