In Java, Integer.numberOfTrailingZeros(i) returns how many 0 bits come after the last 1 bit, counting from the right of the 32-bit form of i.
In everyday terms it tells you how many times a number can be divided by 2 and stay whole. For 8, which is 1000, the answer is 3. For an odd number the answer is 0, and for the number 0 itself it is 32.
A static method of java.lang.Integer (since Java 1.5): call it on the class, as Integer.numberOfTrailingZeros(...). Integer lives in java.lang, so no import is needed.
Syntax
One argument: the int to examine.
Java
int a = Integer.numberOfTrailingZeros(8); // 3 (1000)
int b = Integer.numberOfTrailingZeros(12); // 2 (1100)
int c = Integer.numberOfTrailingZeros(0); // 32
Call
What it does
Integer.numberOfTrailingZeros(i)
Zero bits after the last 1, from 0 to 32.
n >> Integer.numberOfTrailingZeros(n)
Strips every factor of 2 from n, leaving an odd number.
Integer.numberOfTrailingZeros(mask)
The index of the first flag that is set in a bit mask.
Integer.numberOfLeadingZeros(i)
Counts zeros from the left instead.
For 0 the answer is 32, so check for 0 before using the result as a bit position.
Library declarations
Java
// java.lang.Integer
public static int numberOfTrailingZeros(int i)
Parameters
Parameter
Description
i (int)
The number to examine.
Return Value
Return Value
Description
int
The number of zero bits after the lowest set bit, from 0 up to 31, or 32 if i is 0.