Fastest implementation of log2(int) and log2(float)

前端 未结 9 1479
天命终不由人
天命终不由人 2020-12-08 04:57

The question is

Are there any other (and/or faster) implementations of a basic 2log?

Applications

The log2(int) and

9条回答
  •  鱼传尺愫
    2020-12-08 05:14

    There are some integer algorithms here.

    In C#:

    public static uint FloorLog2(uint x)
    {
        x |= (x >> 1);
        x |= (x >> 2);
        x |= (x >> 4);
        x |= (x >> 8);
        x |= (x >> 16);
    
        return (uint)(NumBitsSet(x) - 1);
    }
    
    public static uint CeilingLog2(uint x)
    {
        int y = (int)(x & (x - 1));
    
        y |= -y;
        y >>= (WORDBITS - 1);
        x |= (x >> 1);
        x |= (x >> 2);
        x |= (x >> 4);
        x |= (x >> 8);
        x |= (x >> 16);
    
        return (uint)(NumBitsSet(x) - 1 - y);
    }
    
    public static int NumBitsSet(uint x)
    {
        x -= ((x >> 1) & 0x55555555);
        x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
        x = (((x >> 4) + x) & 0x0f0f0f0f);
        x += (x >> 8);
        x += (x >> 16);
    
        return (int)(x & 0x0000003f);
    }
    
    private const int WORDBITS = 32;
    

    You should look at the original code on the site I linked for the context, particularly what happens with Log2(0).

提交回复
热议问题