Compute fast log base 2 ceiling

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

    If you're compiling for 64-bit processors on Windows, I think this should work. _BitScanReverse64 is an intrinsic function.

    #include 
    __int64 log2ceil( __int64 x )
    {
      unsigned long index;
      if ( !_BitScanReverse64( &index, x ) )
         return -1LL; //dummy return value for x==0
    
      // add 1 if x is NOT a power of 2 (to do the ceil)
      return index + (x&(x-1)?1:0);
    }
    

    For 32-bit, you can emulate _BitScanReverse64, with 1 or 2 calls to _BitScanReverse. Check the upper 32-bits of x, ((long*)&x)[1], then the lower 32-bits if needed, ((long*)&x)[0].

提交回复
热议问题