-2

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.

yfcheng
  • 1
  • 1

1 Answers1

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