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

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

    Think bitwise operators.

    I missunderstood the question the first time. You should produce an int with the leftmost bit set (the others zero). Assuming cmp is set to that value:

    position = sizeof(int)*8
    while(!(n & cmp)){ 
       n <<=1;
       position--;
    }
    

提交回复
热议问题