public class BitTest {
static void binaryPrint (int q) {
if(q == 0) System.out.print(0);
else {
int nlz = Integer.numberOfLeadingZeros(q);
q <<= nlz;
for(int p = 0; p < 32 - nlz; p++) {
int n = (Integer.numberOfLeadingZeros(q) == 0) ? 1 : 0;
System.out.print(n);
q <<= 1;
}
}
System.out.println("");
}
api解释
numberOfLeadingZeros
public static int numberOfLeadingZeros(int i)
在指定 int 值的二进制补码表示形式中最高位(最左边)的 1 位之前,返回零位的数量。如果指定值在其二进制补码表示形式中不存在 1 位,换句话说,如果它等于零,则返回 32。
注意,此方法与基数为 2 的对数密切相关。对于所有的正 int 值 x:
floor(log2(x)) = 31 - numberOfLeadingZeros(x)
ceil(log2(x)) = 32 - numberOfLeadingZeros(x - 1)
返回:
返回在指定 int 值的二进制补码表示形式中最高位(最左边)的 1 位之前的零位的数量;否则,如果该值等于零,则返回 32。
具体还是不懂,求指点。谢谢。