bitwise most significant set bit

后端 未结 10 1971
走了就别回头了
走了就别回头了 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:15

    Just use numberOfTrailingZeros(value) method of Long or Integer class.

    0 讨论(0)
  • 2020-12-20 20:19

    Successive approximation will minimize the iterations to five loops:

    unsigned int mostSignificantBit(uint32_t val) {
      unsigned int bit = 0;
    
      /* 4 = log(sizeof(val) * 8) / log(2) - 1 */
      for(int r = 4; r >= 0 ; --r) {
        unsigned shift = 1 << r; /* 2^r */
        uint32_t sval = val >> shift;
        if (sval) {
            bit += shift;
            val = sval;
        }
      }
      return bit;
    }
    
    0 讨论(0)
  • 2020-12-20 20:23

    Not the most efficient, perhaps, but this should work::

    public int firstBit(int i) {
        return i < 0 ? 31 : i == 0 ? 0 : Integer.toString(i, 2).length();
    }
    
    0 讨论(0)
  • 2020-12-20 20:24

    If you insist on directly using bitwise operators, you can try something like this:

    private int mostSignificantBit(int myInt){
      int mask = 1 << 31;
      for(int bitIndex = 31; bitIndex >= 0; bitIndex--){
        if((myInt & mask) != 0){
          return bitIndex;
        }
        mask >>>= 1;
      }
      return -1;
    }
    

    We initialize the mask to 1 << 31 because that represents a 1 followed by 31 0's. We use that value to test if index 31 (the 32nd spot) is a 1. When we and this value with myInt, we get a 0 unless the corresponding bit is set in myInt. If this is the case, we return that bitIndex. If not, then we shift the mask to the right by 1 and try again. We repeat until we run out of places to shift, in which case it means none of the bits were set (maybe you want to throw an exception here instead of returning -1).

    Note that this will return the value 0 for 1 and 6 for 64 (1000000 in binary). You can adjust that if you prefer. Note also that I used the unsigned right operator rather than the signed right shift. This is because the intent here is to deal with raw bits rather than their signed interpretation, but it doesn't matter in this instance since all negative values will terminate in the first iteration of the loop before shifting occurs.

    0 讨论(0)
提交回复
热议问题