Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计算Java中的前导零(clz)或前导零数(nlz)_Java_Binary_Converter - Fatal编程技术网

计算Java中的前导零(clz)或前导零数(nlz)

计算Java中的前导零(clz)或前导零数(nlz),java,binary,converter,Java,Binary,Converter,我需要二进制的int32作为00100000或int127作为0111111。 变量Integer.toBinaryString仅返回1的结果。 如果我以这种方式构建for循环: for (int i= 32; i <= 127; i + +) { System.out.println (i); System.out.println (Integer.toBinaryString (i)); } for(int i=32;i 2和0111111->1按如下方式计算前导零的数量: int

我需要二进制的
int32
作为
00100000
int127
作为
0111111
。 变量
Integer.toBinaryString
仅返回1的结果。 如果我以这种方式构建for循环:

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

for(int i=32;i 2和0111111->1

按如下方式计算前导零的数量:

int lz = 8;
while (i)
{
    lz--;
    i >>>= 1;
}
当然,这假设数字不超过255,否则,您将得到负面结果。

如何

int lz = Integer.numberOfLeadingZeros(i & 0xFF) - 24;
int tz = Integer.numberOfLeadingZeros(i | 0x100); // max is 8.

有效的解决方案是int-ans=8-(log2(x)+1)

您可以计算log2(x)=logy(x)/logy(2)

测试声明:

int leadingZeros = new UtilsInt.leadingZerosInt(255); // 8
测试输出:

checking if bit: 32 is set |00000000 00000000 00000000 11111111
checking if bit: 31 is set |00000000 00000000 00000000 01111111
checking if bit: 30 is set |00000000 00000000 00000000 00111111
checking if bit: 29 is set |00000000 00000000 00000000 00011111
checking if bit: 28 is set |00000000 00000000 00000000 00001111
checking if bit: 27 is set |00000000 00000000 00000000 00000111
checking if bit: 26 is set |00000000 00000000 00000000 00000011
checking if bit: 25 is set |00000000 00000000 00000000 00000001
bits in this integer from: 24 up to last are not set (i'm counting from msb->lsb)

考虑格式化输出,以便引入前导零。这个解决方案几乎等于由Martijn Courteaux给出的解决方案,Log2(x)给出二进制字符串(x)的长度。没有前导零。所以8-lengthOfString_没有前导零给你的答案你是什么意思,32的正确解是3,它工作正常!好吧,我没有注意到二进制计数从pow(2,0)开始,所以从答案中减去一,答案应该是严格的整数,而不是四舍五入。这是一个非常好的答案!如果可以的话,我会多次向上投票。谢谢!这种方法非常慢,因为它会创建一个临时字符串对象。建议使用整数方法。@antiguru:近两年后看到这一点,我决定我必须改变它。这太可怕了。
checking if bit: 32 is set |00000000 00000000 00000000 11111111
checking if bit: 31 is set |00000000 00000000 00000000 01111111
checking if bit: 30 is set |00000000 00000000 00000000 00111111
checking if bit: 29 is set |00000000 00000000 00000000 00011111
checking if bit: 28 is set |00000000 00000000 00000000 00001111
checking if bit: 27 is set |00000000 00000000 00000000 00000111
checking if bit: 26 is set |00000000 00000000 00000000 00000011
checking if bit: 25 is set |00000000 00000000 00000000 00000001
bits in this integer from: 24 up to last are not set (i'm counting from msb->lsb)