首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Java中计数前导零(clz)或前导零数(nlz)

在Java中计数前导零(clz)或前导零数(nlz)
EN

Stack Overflow用户
提问于 2014-01-25 12:57:54
回答 3查看 4.2K关注 0票数 3

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

代码语言:javascript
运行
复制
for (int i= 32; i <= 127; i + +) {
System.out.println (i); 
System.out.println (Integer.toBinaryString (i));
}

从二进制数来看,我需要前导零(计数前导零)或前导零数(Nlz)的数目,我实际上是指0的确切数字,例如:在00100000 -> 2和0111111->1。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-01-25 13:02:16

按以下方式计算前导零的数目:

代码语言:javascript
运行
复制
int lz = 8;
while (i)
{
    lz--;
    i >>>= 1;
}

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

票数 1
EN

Stack Overflow用户

发布于 2014-01-25 13:33:50

怎么样

代码语言:javascript
运行
复制
int lz = Integer.numberOfLeadingZeros(i & 0xFF) - 24;
int tz = Integer.numberOfLeadingZeros(i | 0x100); // max is 8.
票数 11
EN

Stack Overflow用户

发布于 2016-06-27 13:45:36

代码语言:javascript
运行
复制
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)");
         }
    }
}

测试声明:

代码语言:javascript
运行
复制
int leadingZeros = new UtilsInt.leadingZerosInt(255); // 8

测试输出:

代码语言:javascript
运行
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21350827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档