Java 按位移位运算符。签名和未签名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2244387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bitwise shift operators. Signed and unsigned
提问by
I'm practising for the SCJP exam using cram notes from the Internet.
我正在使用互联网上的补习笔记为 SCJP 考试练习。
According to my notes the >>
operator is supposed to be signed right shift, with the sign bit being brought in from the left. While the left shift operator <<
is supposed to preserve the sign bit.
根据我的笔记,>>
运算符应该被右移签名,符号位是从左边引入的。而左移运算符<<
应该保留符号位。
Playing around however, I'm able to shift the sign with the <<
operator (f.e. Integer.MAX_VALUE << 1
evaluates to -2
, while I'm never able to shift the sign with the >>
operator.
然而,在玩弄时,我可以用<<
操作符移动符号(feInteger.MAX_VALUE << 1
评估为-2
,而我永远无法用>>
操作符移动符号。
I must be misunderstanding something here, but what?
我一定在这里误解了一些东西,但是什么?
回答by Roman
">>" is signed because it keeps the sign. It uses the most left digit in binary representation of a number as a filler. For example:
“>>”是有符号的,因为它保留了符号。它使用数字的二进制表示中最左边的数字作为填充符。例如:
| this value is used as a filler
11011011
>> 11101101
01010010
>> 00101001
">>>" is unsigned version of this operator. It always use zero as a filler:
>>>" 是此运算符的未签名版本。它总是使用零作为填充符:
11011011
>>> 01101101
01010010
>>> 00101001
In binary representation the most left digit determines sign of the number. So, if it's '1' then we have negative value and if it's '0' - then our number is positive. That's why using the most left digit as a filler allows to keep sign permanent.
在二进制表示中,最左边的数字决定了数字的符号。所以,如果它是“1”,那么我们就有负值,如果它是“0”——那么我们的数字就是正值。这就是为什么使用最左边的数字作为填充符可以保持符号永久。
回答by Jacob Zimmerman
The idea behind the shifts is that they can act as multiplying and dividing by powers of 2 ( << 1 is equivalent to *= 2, >> 2 is equivalent to /= 4), which is why the signed version of shifting exists. Unsigned shifting doesn't preserve negatives, necessarily, though. The << operator doesn't actually preserve the sign, as you suggest; it simply happens to in your example. Try doing a left shift on 2,147,483,647; it doesn't stay positive. The reason that they don't bother trying to make a 'signed' left shift is because, if the number shifts from positive to negative (or viceversa), then you went outside the bounds of the variable type anyway.
移位背后的想法是它们可以作为乘以和除以 2 的幂(<< 1 相当于 *= 2,>> 2 相当于 /= 4),这就是为什么存在有符号版本的移位。但是,无符号移位不一定会保留负数。正如您所建议的,<< 运算符实际上并没有保留符号;它只是发生在你的例子中。尝试在 2,147,483,647 上左移;它不会保持积极。他们不费心尝试进行“有符号”左移的原因是,如果数字从正数变为负数(或反之亦然),那么无论如何你都超出了变量类型的范围。