Find out number of bits needed to represent a positive integer in binary?

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.

Leave a Comment