简体   繁体   English

31 在这个方法中代表什么?

[英]What does the 31 represent in this method?

I have this function to find log of base 2 but I dont understand the meaning of the 31.我有这个 function 来查找 base 2 的日志,但我不明白 31 的含义。

  public static void loggg(int n){
        int result = 0;
        for(int i = 0; (n << i & 1 << 31) == 0; i++){
            result = (31-i-1);
            System.out.println( "result " +result);
        }
}

this is my output.这是我的 output。 it seems like its a max number.它似乎是一个最大数量。

result 30
result 29
result 28
result 27
result 26
result 25
result 24
result 23
result 22
result 21
result 20
result 19
result 18
result 17
result 16
result 15
result 14
result 13
result 12
result 11
result 10
result 9
result 8
result 7
result 6
result 5
result 4
(n << i & 1 << 31) == 0

is an obscure way of writing是一种晦涩难懂的写作方式

(n << i) >= 0

1 << 31 is the binary number 10000000 00000000 00000000 00000000 . 1 << 31是二进制数10000000 00000000 00000000 00000000 It's 1, shifted left 31 times.它是 1,左移 31 次。

X & 1 << 31 is a mask, checking if bit 31 is set to 1 in X . X & 1 << 31是一个掩码,检查X中的第 31 位是否设置为 1。

Bit 31 in a signed 32-bit integer is the sign bit.带符号的 32 位 integer 中的第 31 位是符号位。 So X & 1 << 31 == 0 is just checking if X is non-negative.所以X & 1 << 31 == 0只是检查X是否为非负数。

You said this finds the log to the base 2. But since you are working with integers it really only finds the log of the highest power of 2 <= n您说这会找到以 2 为底的对数。但是由于您使用的是整数,因此它实际上只能找到 2 <= n的最高幂的对数

An easier way (but not as interesting) is to simply do the following.一种更简单的方法(但不那么有趣)是简单地执行以下操作。

System.out.println(31-Integer.numberOfLeadingZeros(n));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM