需要帮助才能理解java中的一段代码

时间:2017-05-30 05:27:25

标签: java

static long nextPowerOf2(long n)
{
    n--;
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    n++;
    return n;
}

我正在博客中阅读这个java示例代码。我面临着难以理解的代码。请解释一下这个函数的作用是什么?

1 个答案:

答案 0 :(得分:2)

正如方法的名称所示,它返回的是下一个最接近且大于n的数字,即2的幂。

您需要自己运行此代码,添加print语句并查看代码执行的中间结果。

如果你调用方法nextPowerOf2(6),这将在方法内部发生:

n--; // n becomes 5;
n |= n >> 1; // This is equivalent to n = n | n >> 1.
            // Bit shift >> has higher precedence than bitwise OR |.
            // This is why it becomes 7. Try it yourself and read about
            // these operators.
n |= n >> 2; // n is 7
n |= n >> 4; // n is 7
n |= n >> 8; // n is 7
n |= n >> 16; // n is 7
n++; // n is 8
return n; // return n which is equal to 8 - the next nearest to 6 power of 2.

希望这有帮助。