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

后端 未结 27 3117
终归单人心
终归单人心 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条回答
  •  天涯浪人
    2020-11-22 04:12

    A version in C using successive approximation:

    unsigned int getMsb(unsigned int n)
    {
      unsigned int msb  = sizeof(n) * 4;
      unsigned int step = msb;
      while (step > 1)
     {
        step /=2;
        if (n>>msb)
         msb += step;
       else
         msb -= step;
     }
      if (n>>msb)
        msb++;
      return (msb - 1);
    }
    

    Advantage: the running time is constant regardless of the provided number, as the number of loops are always the same. ( 4 loops when using "unsigned int")

提交回复
热议问题