gpt4 book ai didi

java - 移位问题

转载 作者:行者123 更新时间:2023-11-29 07:59:15 25 4
gpt4 key购买 nike

给定以下代码:

public class Something {
public static void main(String[] args) {
int num = 1;

num <<= 32;
System.out.println(num);

num = 1;
for (int i = 0 ; i < 32; i++)
num <<= 1;
System.out.println(num);
}
}

第一个输出(从 num <<= 32)是 1。

第二个输出(来自 for 循环)是 0。

我不明白..我看起来是一样的..两种方式都将“1”位 (lsb) 移位 32 次,结果不同。

谁能解释一下?

提前致谢。

最佳答案

Can anyone explain?

当然。基本上,int 上的移位操作会屏蔽正确的操作数以获取 [0, 31] 范围内的值。 long 的移位操作将其屏蔽以获取 [0, 63] 范围内的值。

所以:

num <<= 32;

相当于:

num <<= 0;

来自 section 15.19 of the JLS :

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

关于java - 移位问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15485016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com