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:
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))
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;
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 BitSet
seems to me to be the appropriate data structure.
Integer.toBinaryString(value).length()
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;
}