[英]Logical right shift operator in java
I am beginner to java... I have tried very much but could not find the way the following line 我是Java的初学者...我已经尝试了很多,但是找不到以下行的方式
System.out.println (-1>>>1); System.out.println(-1 >>> 1);
gives 2147483647 ? 给2147483647?
Can anyone help me ? 谁能帮我 ?
This is because the binary representation of -1
is 11111111111111111111111111111111
. 这是因为-1
的二进制表示形式是11111111111111111111111111111111
。 When you perform an unsigned right bit-shift operation ( >>>
) on it it moves all of the bits right by the argument ( 1
in this case) and fills in empty spaces on the left with zeros so you get 01111111111111111111111111111111
which is the binary representation of Integer.MAX_VALUE = 2147483647
(not sure where you got 2147483648 from). 当您在其上执行无符号右移操作( >>>
)时,它会将所有位向右移至参数(在本例中为1
),并用零填充左侧的空白区域,从而得到01111111111111111111111111111111
,即Integer.MAX_VALUE = 2147483647
二进制表示形式Integer.MAX_VALUE = 2147483647
(不确定从何处获得2147483648)。
>>>
is the bitwise right-shift operator, with 0 sign extension - in other words, all bits "incoming" from the left are filled with 0s. >>>
是按位右移运算符,符号扩展为0-换句话说,从左侧“传入”的所有位均填充0。
-1 is represented by 32 bits which are all 1. When you shift that right by 1 bit with 0 sign extension, you end up with a value which has the 31 bottom bits still 1, but 0 for the top bit (the sign bit), so you end up with Integer.MAX_VALUE
- which is 2147483647, not 2147483648 as your post states. -1由全部为1的32位表示。当您将其右移1位并加0符号扩展时,最终得到一个值,该值的31个最低位仍为1,但最高位为0(符号位) ),因此您最终得到的是Integer.MAX_VALUE
-2147483647,而不是帖子所声明的2147483648。
Or in JLS terms, from section 15.19 : 或以JLS的说法,来自第15.19节 :
The value of
n >>>
s
isn
right-shifteds
bit positions with zero-extension, where:n >>>
s
的值为零扩展的n
个右移s
位位置,其中:If
n
is positive, then the result is the same as that ofn >> s
. 如果n
为正,则结果与n >> s
。If
n
is negative and the type of the left-hand operand is int, then the result is equal to that of the expression(n >> s) + (2 << ~s)
. 如果n
为负,并且左侧操作数的类型为int,则结果等于表达式(n >> s) + (2 << ~s)
。If
n
is negative and the type of the left-hand operand is long, then the result is equal to that of the expression(n >> s) + (2L << ~s)
. 如果n
为负,并且左侧操作数的类型为long,则结果等于表达式(n >> s) + (2L << ~s)
。
This definition ends up being a bit of a pain to work with - it's easier to just work with the "0 sign extension right-shift" explanation, IMO. 使用此定义最终会有些麻烦-仅使用IMO的“ 0符号扩展右移”说明会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.