为什么-1右移1 = -1在Java中? [英] Why is -1 right shift 1 = -1 in Java?

查看:491
本文介绍了为什么-1右移1 = -1在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题<一来到href=\"http://stackoverflow.com/questions/20439767/why-is-1-zero-fill-right-shift-1-2147483647-for-integers-in-java\">\"Why为-1补零右转向的Java 1 = 2147483647整数?

我的理解填零的概念,直接从上面的问题的答案移位得很清楚。但是,当我试图找到-1 >> 1,我得到一个完全复杂的答案,我觉得很难理解。

I understood the concept of zero fill right shift perfectly well from the above question's answer. But when I tried to find -1>>1, I am getting a totally complex answer which I felt difficult to understand.


-1 in binary form is as follows: 11111111111111111111111111111111
After flipping the bits, I got:  00000000000000000000000000000000
Upon adding 1 to it, I got:      00000000000000000000000000000001
Now shifting one position right: 00000000000000000000000000000000 
After flipping the bits, I got:  11111111111111111111111111111111
Now adding 1 to it:              00000000000000000000000000000000

我不明白怎么1 -1 >> -1本身,然后呢?

I don't understand how -1>>1 is -1 itself, then?

推荐答案

当你做一个正常的右移(即使用&GT;&GT; ,也称为的算术的右移,而不是&GT;&GT;&GT; ,这是一个的逻辑的右移)时,号的符号扩展

When you do a normal right-shift (i.e. using >>, also known as an arithmetic right shift, as opposed to >>>, which is a logical right shift), the number is sign extended.

这是如何工作如下:

当我们右移,我们得到的号码前面的空白点,像这样:

When we right-shift we get an empty spot in front of the number, like so:

 11111111111111111111111111111111
 ?1111111111111111111111111111111(1)  (right-shift it one place)

最后一个 1 被移出,并在来了

现在,我们该怎么填写取决于我们如何转变。

Now, how we fill in the ? is dependent on how we shift.

如果我们做的逻辑移位的(即&GT;&GT;&GT; ),我们简单地用填充0
如果我们做一个的算术移位的(即&GT;&GT; ),我们从原来的号码的第一位填充,即符号位的(因为它是 1 如果数字为负,而 0 如果不)。这就是所谓的符号扩展。

If we do a logical shift (i.e. >>>), we simply fill it with 0. If we do a arithmetic shift (i.e. >>), we fill it with the first bit from the original number, i.e. the sign bit (since it's 1 if the number is negative, and 0 if not). This is called sign extension.

因此​​,在这种情况下, -1 GT;&GT; 1 登录扩展了 1 ,离开原来的 1

So, in this case, -1 >> 1 sign-extends the 1 into the ?, leaving the original -1.

  • Arithmetic shift on Wikipedia
  • Logical shift on Wikipedia

这篇关于为什么-1右移1 = -1在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆