gpt4 book ai didi

java 位操作 >>> 移位

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:35:55 26 4
gpt4 key购买 nike

为什么如果

int x = -1 // binary: 11111111111111111111111111111111
x = x >>> 31;

我们有 00000000000000000000000000000001

但是如果

int x = -1
x = x >>> 32;

我们有 11111111111111111111111111111111(又是 -1)

但不是 00000000000000000000000000000000 吗?

最佳答案

来自 Section 15.19 of 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.

强调我的。所以:

x >>> n

相当于:

x >>> n & 0x1f  // or x >>> n % 32

因此,x >>> 32 等同于 x >>> 32 & 0x1f <==> x >>> 0 == x

因此经验法则是,每当您将数字移动 32(int32 位),你会得到相同的值。

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

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