/**
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 32if 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 base2. 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, or32if the value is equal to zero.
Since:
1.5
**/
publicstatic int numberOfLeadingZeros(int i) {
// HD, Figure 5-6if (i == 0)
return32;
//例子:假设有如下二进制数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 0000if (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的个数是4return n;
}