Compute fast log base 2 ceiling

前端 未结 14 674
栀梦
栀梦 2020-11-28 11:35

What is a fast way to compute the (long int) ceiling(log_2(i)), where the input and output are 64-bit integers? Solutions for signed or unsigned integers are ac

14条回答
  •  没有蜡笔的小新
    2020-11-28 12:27

    This algorithm has already been posted, but the following implementation is very compact and should optimize into branch-free code.

    int ceil_log2(unsigned long long x)
    {
      static const unsigned long long t[6] = {
        0xFFFFFFFF00000000ull,
        0x00000000FFFF0000ull,
        0x000000000000FF00ull,
        0x00000000000000F0ull,
        0x000000000000000Cull,
        0x0000000000000002ull
      };
    
      int y = (((x & (x - 1)) == 0) ? 0 : 1);
      int j = 32;
      int i;
    
      for (i = 0; i < 6; i++) {
        int k = (((x & t[i]) == 0) ? 0 : j);
        y += k;
        x >>= k;
        j >>= 1;
      }
    
      return y;
    }
    
    
    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
      printf("%d\n", ceil_log2(atol(argv[1])));
    
      return 0;
    }
    

提交回复
热议问题