Compute fast log base 2 ceiling

前端 未结 14 669
栀梦
栀梦 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:36

    The code below is simpler and will work as long as the input x >= 1. input clog2(0) will get an undefined answer (which makes sense because log(0) is infinity...) You can add error checking for (x == 0) if you want:

    unsigned int clog2 (unsigned int x)
    {
        unsigned int result = 0;
        --x;
        while (x > 0) {
            ++result;
            x >>= 1;
        }
    
        return result;
    }
    

    By the way, the code for the floor of log2 is similar: (Again, assuming x >= 1)

    unsigned int flog2 (unsigned int x)
    {
        unsigned int result = 0;
        while (x > 1) {
            ++result;
            x >>= 1;
        }
    
        return result;
    }
    

提交回复
热议问题