Java中的右移运算符功能
int z = -1; int m = z>>1; System.out.println("the values is " +m);
输出是
the values is -1
但我怀疑它是如何在内部发生的,有什么能解释吗?一步一步的程序
int z=2;int m=z>>;1;
二进制中的z值
00000000 00000000 00000000 00000010
值移位后,二进制中的m值将为
00000000 00000000 00000000 00000001
,当我打印m
值时,它将作为1
,但我的问题是,如果我对z变量使用负值,当我用-1分配z值时,会发生什么,为什么输出变量本身有-1?(会发生两种情况吗?)
# 1 楼答案
如前所述in JLS Sec 15.19:
所以,你在计算
-1 >> 1 == floor(-1 / 2) == floor(-0.5) = -1