bitwise most significant set bit

后端 未结 10 1979
走了就别回头了
走了就别回头了 2020-12-20 19:50

I want to find the most significant bit that is set to 1. I have tried every possible way from & to ORing all of the bits from 1 t

10条回答
  •  萌比男神i
    2020-12-20 20:11

    Though there is an answer accepted, I have another ways to share which I think is easier.

    If you want to use bitwise operations, here is the way. Basically, I am right-shifting the integer until it become zero. No mask is required.

    private static int mostSignificantBit(int myInt){
        int i = 0;
        while (myInt != 0) {
            ++i;
            myInt >>>= 1;
        }
        return i;
    }
    

    Another way is calculate it mathematically:

    private static int mostSignificantBit(int myInt){
        if (myInt == 0) return 0;    // special handling for 0
        if (myInt < 0) return 32;    // special handling for -ve
    
        return (int)(Math.log(myInt)/Math.log(2)) +1;
    }
    

提交回复
热议问题