Java中的按位右移运算符 [英] Bitwise right shift operator in Java

查看:196
本文介绍了Java中的按位右移运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,-4 >> 2给出-1,而-5 >> 2给出-2.有人可以解释为什么吗? 这是示例代码:

In Java, -4 >> 2 gives -1 but -5 >> 2 gives -2. Can anybody explain why? Here is a sample code:

byte r=-5;
r>>=2;
System.out.println(r);

在这种情况下>>和>>>运算符也给出相同的答案.谁能解释一下?

Also in this scenario >> and >>> operators give the same answer. Can anyone explain that as well?

推荐答案

您可以看看这些内容.使用二进制补码表示法,-4-5的位仅显示为了简洁起见,最后8位:

You can take a look at the bits. Using two's complement notation, the bits for -4 and -5 are, showing only the last 8 bits for brevity:

-4: 1111 1100      
-5: 1111 1011

右移2位,带符号扩展名:

Bit shifting to the right 2 positions, with sign extension:

-4 >> 2: 1111 1111 (-1)
-5 >> 2: 1111 1110 (-2)

通常,您会想到>>>不使用符号扩展名,这是事实,但在这种情况下:

Normally, you think of >>> not using sign extension, and this is true, but in this case:

r >>>= 2;

...对于使用二进制数值提升的移位操作,值r提升为int,但是复合赋值运算符将返回的值强制转换回byte,而移入的零为消失".

... the value r is promoted to int for the bit-shift operation using binary numeric promotion, but the compound assignment operator casts the returned value back to byte, and the shifted-in zero "disappears".

byte r = -5;     // 1111 1100
r >>>= -2;       // promoted to int:   11111111 11111111 11111111 11111010
                 // bit shift:         00111111 11111111 11111111 11111110
                 // cast back to byte: 11111110 (-2)

JLS,第15.26.2节讨论了在化合物中进行的浇铸操作赋值运算符:

The JLS, Section 15.26.2, talks about the casting operation done in compound assignment operators:

形式为E1 op = E2的复合赋值表达式等效于E1 =(T)((E1)op(E2)),其中T是E1的类型,只是E1仅被评估一次.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

也就是说,在这种情况下,将移位的结果回退到byte.

That is, in this case, the result of the bit-shift is casted back to byte.

r的值为-4时,也会发生相同的回退字节操作.

The same cast-back-to-byte operation occurs when the value of r is -4.

请注意,如果未完成分配部分,那么您将不会看到相同的答案,因为它不会将结果转换回byte:

Note that if the assignment part wasn't done, then you wouldn't see the same answer, because it wouldn't cast the result back to byte:

System.out.println(r >>> 2);

然后您会看到:

1073741822

这篇关于Java中的按位右移运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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