This was part of a larger programming assignment that was due for me last night. Couldn\'t figure out this problem, but I\'m curious as to how it could be solved.
Th
Fill all of the bits to the right of the most significant one by shifting and OR'ing:
0b 0010 0000 0000 0000 0100 0000 0000 0000
0b 0011 0000 0000 0000 0110 0000 0000 0000
0b 0011 1100 0000 0000 0111 1000 0000 0000
0b 0011 1111 1100 0000 0111 1111 1000 0000
0b 0011 1111 1111 1111 1111 1111 1111 1111
Then shift right and add 1 to leave the most significant one:
0b 0001 1111 1111 1111 1111 1111 1111 1111
0b 0010 0000 0000 0000 0000 0000 0000 0000
Code:
int greatestBitPos(int x) {
int is_nonzero = (x != 0);
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 18);
x = x | (x >> 16);
return (is_nonzero * ((x >> 1) + 1));
}