user3235117 user3235117 - 5 months ago 31
Java Question

count leading zeros (clz) or number of leading zeros (nlz) in Java

I need

int 32
in binary as
00100000
or
int 127
in binary
0111 1111
.
The variant
Integer.toBinaryString
returns results only from 1.
If I build the for loop this way:

for (int i= 32; i <= 127; i + +) {
System.out.println (i);
System.out.println (Integer.toBinaryString (i));
}


And from binary numbers I need the number of leading zeros (count leading zeros (clz) or number of leading zeros (nlz)) I really meant the exact number of 0, such ex: at 00100000 -> 2 and at 0111 1111 - > 1

Answer

Count the number of leading zeros as follows:

int lz = 8;
while (i)
{
    lz--;
    i >>>= 1;
}

Of course, this supposes the number doesn't exceed 255, otherwise, you would get negative results.