问题
In JDK 8:
public static int numberOfLeadingZeros(int i) {
if (i == 0)
return 32;
int n = 1;
// if the first leftest one bit occurs in the low 16 bits
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
n -= i >>> 31;
return n;
}
By judging if the leftest first one bit is in the low x bits.
public static int numberOfTrailingZeros(int i) {
int y;
if (i == 0) return 32;
int n = 31;
// if the rightest first one bit occurs in the low 16 bits
y = i <<16; if (y != 0) { n = n -16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
return n - ((i << 1) >>> 31);
}
By judging if the rightest first one bit is in the low x bits.
Why numberOfTrailingZeros
doesn't use the implementation like numberOfLeadingZeros
?
public static int numberOfTrailingZeros2(int i) {
if (i == 0) return 32;
int n = 0;
if (i << 16 == 0) { n += 16; i >>>= 16; }
if (i << 24 == 0) { n += 8; i >>>= 8; }
if (i << 28 == 0) { n += 4; i >>>= 4; }
if (i << 30 == 0) { n += 2; i >>>= 2; }
if (i << 31 == 0) { n += 1; i >>>= 1; }
return n;
}
And why numberOfLeadingZeros
doesn't use the implementation like numberOfTrailingZeros
?
public static int numberOfLeadingZeros2(int i) {
int y;
if (i == 0) return 32;
int n = 31;
y = i >>>16; if (y != 0) { n = n -16; i = y; }
y = i >>> 8; if (y != 0) { n = n - 8; i = y; }
y = i >>> 4; if (y != 0) { n = n - 4; i = y; }
y = i >>> 2; if (y != 0) { n = n - 2; i = y; }
return n - (i >>> 1);
}
来源:https://stackoverflow.com/questions/59463728/why-integer-numberofleadingzeros-and-numberoftrailingzeros-use-different-impleme