What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

后端 未结 27 2731
终归单人心
终归单人心 2020-11-22 03:35

If I have some integer n, and I want to know the position of the most significant bit (that is, if the least significant bit is on the right, I want to know the position of

27条回答
  •  名媛妹妹
    2020-11-22 04:22

    unsigned int
    msb32(register unsigned int x)
    {
            x |= (x >> 1);
            x |= (x >> 2);
            x |= (x >> 4);
            x |= (x >> 8);
            x |= (x >> 16);
            return(x & ~(x >> 1));
    }
    

    1 register, 13 instructions. Believe it or not, this is usually faster than the BSR instruction mentioned above, which operates in linear time. This is logarithmic time.

    From http://aggregate.org/MAGIC/#Most%20Significant%201%20Bit

提交回复
热议问题