问题描述
我遇到的问题\"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?
推荐答案
当你做一个正常的右移(即使用>>
,也称为的算术的右移,而不是>>>
,这是一个的逻辑的右移)时,号的符号扩展的
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.
如果我们做的逻辑移位的(即>>>
),我们简单地用填充0
。
如果我们做一个的算术移位的(即>>
),我们从原来的号码的第一位填充,即符号位的(因为它是 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;> 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中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!