numberOfLeadingZeros(int i)源码探索

/**
Returns the number of zero bits preceding the highest-order ("leftmost") one-bit in the two's complement binary representation of the specified int value. 
$$返回0位的个数(在最高最左的"1位"之前的"0位"的个数),用二进制表示一个数$$
Returns 32 if the specified value has no one-bits in its two's complement representation, in other words if it is equal to zero.
Note that this method is closely related to the logarithm base 2. For all positive int values x:
floor(log2(x)) = 31 - numberOfLeadingZeros(x)
ceil(log2(x)) = 32 - numberOfLeadingZeros(x - 1)
Returns:
the number of zero bits preceding the highest-order ("leftmost") one-bit in the two's complement binary representation of the specified int value, or 32 if the value is equal to zero.
Since:
1.5
**/
    public static int numberOfLeadingZeros(int i) {
        // HD, Figure 5-6
        if (i == 0)
            return 32;
        //例子:假设有如下二进制数A是0000 1111 1111 1111 1111 1111 1111 1111,
        int n = 1;
        if (i >>> 16 == 0) { n += 16; i <<= 16; }
        if (i >>> 24 == 0) { n +=  8; i <<=  8; }
        if (i >>> 28 == 0) { n +=  4; i <<=  4; }//无符号右移28位后变成0,说明前面至少有4个0;n+=4;n=5;左移4位,所以要A变成 1111 1111 1111 1111 1111 1111 1111 0000
        if (i >>> 30 == 0) { n +=  2; i <<=  2; }//A无符号右移30位不等于0,跳过这个if判断
        n -= i >>> 31;//1111 1111 1111 1111 1111 1111 1111 0000,无符号右移31位后变成0000 0000 0000 0000 0000 0000 0000 0001,十进制表示为1,n -= i >>> 31;n -= 1;n = n - 1 = 5-1 = 4,说明前导0的个数是4
        return n;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值