Count bits used in int

后端 未结 11 1398
梦谈多话
梦谈多话 2020-12-30 15:54

If you have the binary number 10110 how can I get it to return 5? e.g a number that tells how many bits are used? There are some likewise examples listed below:

相关标签:
11条回答
  • 2020-12-30 16:50

    You want to compute the base 2 logarithm of the number - specifically:

    1 + floor(log2(value))

    Java has a Math.log method which uses base e, so you can do:

    1 + Math.floor(Math.log(value) / Math.log(2))
    0 讨论(0)
  • 2020-12-30 16:53

    I think the rounded-up log_2 of that number will give you what you need.

    Something like:

    return (int)(Math.log(value) / Math.log(2)) + 1;
    
    0 讨论(0)
  • 2020-12-30 16:56

    Another solution is to use the length() of a BitSet which according to the API

    Returns the "logical size" ... the index of the highest set bit ... plus one.

    To use the BitSet you need to create an array. So it is not as simple as starting with a pure int. But you get it out of the JDK box - tested and supported. It would look like this:

      public static int bitsCount(int i) {
        return BitSet.valueOf(new long[] { i }).length();
      }
    

    Applied to the examples in the question:

      bitsCount(0b101); // 3
      bitsCount(0b000000011); // 2
      bitsCount(0b11100); // 5
      bitsCount(0b101010101); // 9
    

    When asking for bits the BitSetseems to me to be the appropriate data structure.

    0 讨论(0)
  • 2020-12-30 16:57

    Integer.toBinaryString(value).length()

    0 讨论(0)
  • 2020-12-30 16:58

    If you are looking for the fastest (and without a table, which is certainly faster), this is probably the one:

    public static int bitLength(int i) {
        int len = 0;
    
        while (i != 0) {
            len += (i & 1);
            i >>>= 1;
        }
    
        return len;
    
    }
    
    0 讨论(0)
提交回复
热议问题