Compute fast log base 2 ceiling

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

    The naive linear search may be an option for evenly distributed integers, since it needs slightly less than 2 comparisons on average (for any integer size).

    /* between 1 and 64 comparisons, ~2 on average */
    #define u64_size(c) (              \
        0x8000000000000000 < (c) ? 64  \
      : 0x4000000000000000 < (c) ? 63  \
      : 0x2000000000000000 < (c) ? 62  \
      : 0x1000000000000000 < (c) ? 61  \
    ...
      : 0x0000000000000002 < (c) ?  2  \
      : 0x0000000000000001 < (c) ?  1  \
      :                             0  \
    )
    

提交回复
热议问题