按位移位运算符。已签名和未签名

发布于 2024-08-21 01:23:28 字数 315 浏览 2 评论 0原文

我正在利用互联网上的临时笔记练习 SCJP 考试。

根据我的笔记, >> 运算符应该是有符号右移,符号位从左侧引入。而左移运算符 << 应该保留符号位。

然而,我可以使用 << 运算符来移动符号(fe Integer.MAX_VALUE << 1 计算结果为 -2,虽然我永远无法使用 >> 运算符来移动符号,但

我一定是误解了一些东西,但是什么呢?

I'm practising for the SCJP exam using cram notes from the Internet.

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.

I must be misunderstanding something here, but what?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

流殇 2024-08-28 01:23:28

“>>”已签名,因为它保留了该标志。它使用数字的二进制表示形式中最左边的数字作为填充符。例如:

    | this value is used as a filler 
    11011011 
 >> 11101101  

    01010010
 >> 00101001 

“>>”是该运算符的无符号版本。它总是使用零作为填充符:

    11011011 
>>> 01101101  

    01010010
>>> 00101001

在二进制表示中,最左边的数字决定数字的符号。因此,如果它是“1”,那么我们的值为负值,如果它是“0”,那么我们的数字就是正值。这就是为什么使用最左边的数字作为填充符可以保持符号永久。

">>" 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.

千寻… 2024-08-28 01:23:28

这些移位背后的想法是,它们可以充当 2 的幂的乘法和除法(<< 1 相当于 *= 2,>> 2 相当于 /= 4),这就是带符号版本的原因的转变存在。但无符号移位不一定保留符号。 <<正如您所建议的,运算符实际上并不保留符号;它恰好发生在你的例子中。尝试对 2,147,483,647 进行左移;它不会保持积极的状态。他们不费心尝试进行“有符号”左移的原因是,如果数字从正数变为负数(反之亦然),那么无论如何您都会超出变量类型的范围。

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 the sign, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文