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

时间:2014-01-25 12:57:55

标签: java binary converter

我需要二进制int 32中的00100000或二进制int 127中的0111 1111。 变体Integer.toBinaryString仅返回1的结果。 如果我以这种方式构建for循环:

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

从二进制数字我需要前导零的数量(计数前导零(clz)或前导零(nlz)的数量)我真的是指0的确切数字,例如:00100000 - &gt; 2和0111 1111 - &gt; 1

4 个答案:

答案 0 :(得分:8)

怎么样

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

答案 1 :(得分:1)

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

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

当然,这假设数字不超过255,否则,你会得到负面结果。

答案 2 :(得分:1)

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

你可以计算log 2 (x)= log y (x)/ log y (2)

答案 3 :(得分:0)

public class UtilsInt {

    int leadingZerosInt(int i) {
        return leadingZeros(i,Integer.SIZE);
    }

    /**
     * use recursion to find occurence of first set bit
     * rotate right by one bit & adjust complement
     * check if rotate value is not zero if so stop counting/recursion
     * @param i - integer to check 
     * @param maxBitsCount - size of type (in this case int)
     *                       if we want to check only for:
     *                         positive values we can set this to Integer.SIZE / 2   
     *                         (as int is signed  in java - positive values are in L16 bits)
     */
     private synchronized int leadingZeros(int i, int maxBitsCount) {
         try {
            logger.debug("checking if bit: "+ maxBitsCount 
                                + " is set | " + UtilsInt.intToString(i,8));
            return (i >>>= 1) != 0 ? leadingZeros(i, --maxBitsCount) : maxBitsCount;
         } finally {
             if(i==0) logger.debug("bits in this integer from: " + --maxBitsCount 
                               + " up to last are not set (i'm counting from msb->lsb)");
         }
    }
}

测试声明:

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)