计算"2的幂"数字的最快方法?

Ann*_*inn 8 c++ math

找到2的幂的最快方法是什么,使用一定数量(即2的幂)?

我对数学不是很熟练,所以我不确定如何最好地描述它.但功能将类似于x = 2^y这里y是输出,并且x是输入.这是一个真实表,如果有助于解释它的外观.

0 = f(1)
1 = f(2)
2 = f(4)
3 = f(8)
...
8 = f(256)
9 = f(512)
Run Code Online (Sandbox Code Playgroud)

我已经做了一个这样做的功能,但我担心它不是很有效(或者说优雅).这样做会有更简单,更有效的方法吗?我正在使用它来计算纹理的哪个区域用于缓冲绘制的完成方式,因此每个绘制的对象至少调用一次.这是我到目前为止所做的功能:

uint32 getThePowerOfTwo(uint32 value){
    for(uint32 n = 0; n < 32; ++n){
        if(value <= (1 << n)){
            return n;
        }
    }
    return 32; // should never be called
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 8

基于woolstar的答案 - 我想知道查找表的二进制搜索是否会稍快一些?(看起来好多了)......

int getThePowerOfTwo(int value) {
    static constexpr int twos[] = {
        1<<0,  1<<1,  1<<2,  1<<3,  1<<4,  1<<5,  1<<6,  1<<7,
        1<<8,  1<<9,  1<<10, 1<<11, 1<<12, 1<<13, 1<<14, 1<<15,
        1<<16, 1<<17, 1<<18, 1<<19, 1<<20, 1<<21, 1<<22, 1<<23,
        1<<24, 1<<25, 1<<26, 1<<27, 1<<28, 1<<29, 1<<30, 1<<31
    };

    return std::lower_bound(std::begin(twos), std::end(twos), value) - std::begin(twos);
}
Run Code Online (Sandbox Code Playgroud)

  • @Dave顺便说一句,这里有一个基准,天真的方法胜过其他两个人:[链接到CoLiRu](http://coliru.stacked-crooked.com/a/4d793debca3aafe3) (3认同)
  • @Clairvoire这支持32位,而不仅仅是16位.当您使用更大范围的数字(最多2 ^ 32)时,您应该看到天真实现的更大差异 (2认同)