Find out number of bits needed to represent a positive integer in binary?
Well, you can just count how many times you shift right before you're left with just zero:
int value = 11;
int count = 0;
while (value > 0) {
count++;
value = value >> 1;
}
Well, the answer is pretty simple. If you have an int value:
int log2(int value) {
return Integer.SIZE-Integer.numberOfLeadingZeros(value);
}
The same exists for Long...
[Edit] If shaving milliseconds is an issue here, Integer.numberOfLeadingZeros(int) is reasonably efficient, but still does 15 operations... Expanding a reasonable amount of memory (300 bytes, static) you could shave that to between 1 and 8 operations, depending on the range of your integers.