Compute fast log base 2 ceiling

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

    If you have 80-bit or 128-bit floats available, cast to that type and then read off the exponent bits. This link has details (for integers up to 52 bits) and several other methods:

    http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogIEEE64Float

    Also, check the ffmpeg source. I know they have a very fast algorithm. Even if it's not directly extensible to larger sizes, you can easily do something like if (x>INT32_MAX) return fastlog2(x>>32)+32; else return fastlog2(x);

提交回复
热议问题