bitwise most significant set bit

后端 未结 10 1970
走了就别回头了
走了就别回头了 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条回答
  • 2020-12-20 20:02

    For Little Endian format:

    ((yourByte & yourBitMask) >> msbIndex) && 0x01
    
    0 讨论(0)
  • 2020-12-20 20:04

    Just to add another approach

    public static int mostSignificantBit(int b) {
        for (int i = 1 << 30, j = 0; i > 0; i /= 2, j++) {
               if ((b & i) > 0) {
                return 31-j;
            }
        }
        return -1;
    }
    
    0 讨论(0)
  • 2020-12-20 20:05

    http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#numberOfLeadingZeros%28int%29 You want something like 32 - Integer.numberOfLeadingZeros(value).

    0 讨论(0)
  • 2020-12-20 20:05
    if( value | 0x40 ) return 7;
    else if( value | 0x20 ) return 6;
    else if( value | 0x10 ) return 5;
    else if( value | 0x8 ) return 4;
    else if( value | 0x4 ) return 3;
    else if( value | 0x2 ) return 2;
    else if( value | 0x1 ) return 1;
    
    0 讨论(0)
  • 2020-12-20 20:11

    The slickest implementation I've come across - three iterations and a table lookup.

    unsigned int msb32(unsigned int x)
    {
        static const unsigned int bval[] =
        { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
    
        unsigned int base = 0;
        if (x & 0xFFFF0000) { base += 32/2; x >>= 32/2; }
        if (x & 0x0000FF00) { base += 32/4; x >>= 32/4; }
        if (x & 0x000000F0) { base += 32/8; x >>= 32/8; }
        return base + bval[x];
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题