this is the numberOfLeadingZeros(long i) in Long.java :
public static int numberOfLeadingZeros(long i) {
// HD, Figure 5-6
if (i == 0)
return 64;
int n = 1;
int x = (int)(i >>> 32);
if (x == 0) { n += 32; x = (int)i; }
if (x >>> 16 == 0) { n += 16; x <<= 16; }
if (x >>> 24 == 0) { n += 8; x <<= 8; }
if (x >>> 28 == 0) { n += 4; x <<= 4; }
if (x >>> 30 == 0) { n += 2; x <<= 2; }
n -= x >>> 31;
return n;
}
and the author said it is based floor(log2(x)) = 63 – numberOfLeadingZeros(x) or ceil(log2(x)) = 64 – numberOfLeadingZeros(x – 1),is that true? or maybe i am so stupid that can’t understand?
somebody who can explain it to me? thanks!
The number of digits in a number is
floor(log(num)) + 1(with log in the correct base.) If the total digit space is x, then the number of leading zeros isSo in your case, with 64 total digits and the number in binary
Edit:
>>>is the unsigned right shift operator in Java and<<is a left shift.n >>> 32will shiftn32 bits to the right while filling the empty space with 0s.So the algorithm works as follows:
Shift
i32 bits to the right soxcontains only the upper 32 bits.00000000000000000000000000000000If (a) this is 0, we know the upper 32 bits were 0s so add 32 to the leading zero count and concentrate on the lower 32 bits. (b) Otherwise, this is nonzero so the number has less than 32 leading zeros. Concentrate on the upper 32 bits.
Shift
x16 bits to the right.0000000000000101By the same process: (a) If this is 0, add 16 to the leading zero count and concentrate on the next lowest 16 bits (by shifting them left into the area where we’re working.) (b) If this is nonzero, then we have less than 16 leading zeros to add.
Repeat for the next byte, then the next 4 bits, 2 bits, and the final bit.