签署左移行为 [英] Signed left shift behaviour
问题描述
public class Shift {
public static void main(String[] args) {
for(int i = 0; i < 32; ++i){
System.out.println(-0x55555555 << i);
}
}
}
运行上面的代码给出了以下输出
Running the above code gives the following output
-1431655765
1431655766
-1431655764
1431655768
-1431655760
1431655776
-1431655744
1431655808
-1431655680
1431655936
-1431655424
1431656448
-1431654400
1431658496
-1431650304
1431666688
-1431633920
1431699456
-1431568384
1431830528
-1431306240
1432354816
-1430257664
1434451968
-1426063360
1442840576
-1409286144
1476395008
-1342177280
1610612736
-1073741824
-2147483648
使用其他值(64)进行测试可获得更预期的结果
While testing with an other value (64) gives a more expected result
public class Shift {
public static void main(String[] args) {
for(int i = 0; i < 32; ++i){
System.out.println(-0x40 << i);
}
}
}
输出
-64
-128
-256
-512
-1024
-2048
-4096
-8192
-16384
-32768
-65536
-131072
-262144
-524288
-1048576
-2097152
-4194304
-8388608
-16777216
-33554432
-67108864
-134217728
-268435456
-536870912
-1073741824
-2147483648
0
0
0
0
0
0
在规格(§15.19)据说:
n<<< s是n个左移位位;这相当于(即使发生溢出)乘以2乘以幂。
有人可以解释第一个输出的原因?
Can someone explain the why's of the first output?
推荐答案
n<<< s是n个左移位位;这相当于(即使发生溢出)乘以2乘以幂。
The value of n << s is n left-shifted s bit positions; this is equivalent (even if overflow occurs) to multiplication by two to the power s.
这是真的:这正是结果如果由于溢出而将 -0x55555555
乘以 s
的幂,你会得到。特别是, 0x55555555
具有交替的0和1,因此您将0和1交替转换为符号位,因此符号每次都会翻转。
And it's true: this is exactly the result you'd get if you multiplied -0x55555555
by two to the power of s
, due to overflow. In particular, 0x55555555
has alternating 0s and 1s, so you're shifting alternating 0s and 1s into the sign bit, so the sign is flipping every time.
这篇关于签署左移行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!