I know that when getting the least significant bit in a number is by doing x &= -x
. This clears out all the other bits except the least set one. I'm just wondering now how can I easily get the most significant bit. I can come up with a bit shifting code, but probably not ideal in terms of complexity.
Asked
Active
Viewed 243 times
-2

yfcheng
- 1
- 1
-
2Uh, the easiest way to get the least significant bit is probably just `x&1` – Mooing Duck Apr 20 '16 at 20:36
-
2floor(log2(value)). Complexity for whom? What language, what platform? – TessellatingHeckler Apr 20 '16 at 20:44
-
2Which language?? Any _real_ tags? Most/least in the _type_ or most/least _set in a particular number_? Your wording is quite vague. – underscore_d Apr 20 '16 at 20:47
-
Related: [Algorithm for finding the smallest power of two that's greater or equal to a given value](http://stackoverflow.com/q/364985/4279) – jfs Apr 20 '16 at 21:00
1 Answers
0
#include <climits>
// have the compiler determine how many bits we need to right shift so only
// the biggest will be left
constexpr unsigned shiftby = 1<<(CHAR_BIT*sizeof(unsigned)-1);
// then at runtime: shift it.
unsigned result = static_cast<unsigned>(x)>>shiftby;
While this appears complex, at runtime it's literally just a single shift operation. This only works for types int
and unsigned
.

Mooing Duck
- 64,318
- 19
- 100
- 158
-
Nice C++ solution for finding the most significant bit in this particular type, but I suspect the OP really wants the MSbit in a given _number_, based on the earlier phrase "least set". – underscore_d Apr 20 '16 at 20:51