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

后端 未结 27 2767
终归单人心
终归单人心 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:16

    The code:

        // x>=1;
        unsigned func(unsigned x) {
        double d = x ;
        int p= (*reinterpret_cast(&d) >> 52) - 1023;
        printf( "The left-most non zero bit of %d is bit %d\n", x, p);
        }
    

    Or get the integer part of FPU instruction FYL2X (Y*Log2 X) by setting Y=1

提交回复
热议问题