计数前导零(CLZ),或在Java的前导零(NLZ)的数量 [英] count leading zeros (clz) or number of leading zeros (nlz) in Java
问题描述
我需要 INT 32
以二进制为 00100000
或 INT 127
二进制 0111 1111
。
变体 Integer.toBinaryString
仅从1返回结果。
如果我建立循环是这样的:
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));
}
和二进制数,我需要前导零的数量(计数前导零(CLZ)或前导零(NLZ)的数量)我真的意味着0的确切数字,例如例如:在00100000 - > 2,并在0111 1111 - > 1
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
推荐答案
计数前导零的数目如下:
Count the number of leading zeros as follows:
int lz = 8;
while (i)
{
lz--;
i >>>= 1;
}
当然,这个假设的数量不超过255,否则,你会得到阴性结果。
Of course, this supposes the number doesn't exceed 255, otherwise, you would get negative results.
这篇关于计数前导零(CLZ),或在Java的前导零(NLZ)的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!