In Java, Integer.numberOfLeadingZeros(i) returns how many 0 bits come before the first 1 bit, counting from the left of the 32-bit form of i.
The number 1 has 31 leading zeros, because only the last of its 32 bits is set. The number 0 has no 1 bit at all, so its answer is 32, and every negative number has 0 leading zeros because its top bit is already 1.
A static method of java.lang.Integer (since Java 1.5): call it on the class, as Integer.numberOfLeadingZeros(...). Integer lives in java.lang, so no import is needed.
Syntax
One argument: the int to examine.
Java
int a = Integer.numberOfLeadingZeros(1); // 31
int b = Integer.numberOfLeadingZeros(255); // 24
int c = Integer.numberOfLeadingZeros(-1); // 0
Call
What it does
Integer.numberOfLeadingZeros(i)
Zero bits before the first 1, from 0 to 32.
32 - Integer.numberOfLeadingZeros(i)
The number of binary digits needed (the bit length).
31 - Integer.numberOfLeadingZeros(i)
The position of the top bit, which is also the floor of log base 2.
Integer.numberOfTrailingZeros(i)
Counts zeros from the right instead.
The answer is 32 for 0 and 0 for any negative number. Use it with care in a formula, because both are special cases.
Library declarations
Java
// java.lang.Integer
public static int numberOfLeadingZeros(int i)
Parameters
Parameter
Description
i (int)
The number to examine.
Return Value
Return Value
Description
int
The number of zero bits in front of the highest set bit: 0 for negative numbers, up to 31 for 1, and 32 for 0.