java右移位怎么算,Java中的按位右移运算符

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?

解决方案

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

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;

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

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

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.

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

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

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);

Then you would see:

1073741822

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值