What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

后端 未结 27 2777
终归单人心
终归单人心 2020-11-22 03:35

If I have some integer n, and I want to know the position of the most significant bit (that is, if the least significant bit is on the right, I want to know the position of

27条回答
  •  旧时难觅i
    2020-11-22 04:28

    This should be lightning fast:

    int msb(unsigned int v) {
      static const int pos[32] = {0, 1, 28, 2, 29, 14, 24, 3,
        30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19,
        16, 7, 26, 12, 18, 6, 11, 5, 10, 9};
      v |= v >> 1;
      v |= v >> 2;
      v |= v >> 4;
      v |= v >> 8;
      v |= v >> 16;
      v = (v >> 1) + 1;
      return pos[(v * 0x077CB531UL) >> 27];
    }
    

提交回复
热议问题