Java添零右移,对于Java中的整数,为什么-1为零填充右移1 = 2147483647?

For the program below:

public class ZeroFillRightShift

{

public static void main(String args[])

{

int x = -1;

int y = x>>>1;

System.out.println("x = " + x);

System.out.println("y = " + y);

}

I get the output as follows:

x = -1

y = 2147483647

The result that I got for -1>>>1 is 2147483647. If it’s the sign bit that has to be shifted, as I learned, the result should be 1073741824. Why is it 2147483647 then?

The following image illustrates my problem more clearly:

UYcVq.png

解决方案

The unsigned right shift operator ">>>" shifts a zero into the

leftmost position, while the leftmost position after ">>" depends on

sign extension.

So, -1 is shifted right one bit with zero-extension, which means it will insert a 0 into the leftmost position. Remember, we're dealing with two's complement here:

-1 is: 11111111111111111111111111111111 or 0xFFFFFFFF in Hex

-1 >>> 1 is 01111111111111111111111111111111 or 0x7FFFFFFF in Hex,

which is 231 - 1 == 2147483647

Here's a JLS reference for shift operators.

You seemed to be confused about two's complement. 31 bits are used for the value and the bit farthest to the left is used for the sign. Since you're only shifting by 1 bit, the signed bit becomes a 0, which means positive, and the result is the greatest positive number than an int can represent.

Perhaps another example will help. Let's consider the following:

System.out.println(-2 >> 1); //prints -1

-2 = 11111111111111111111111111111110

If we use a signed right shift, we get: 11111111111111111111111111111111, which is -1. However, if we do:

System.out.println(-2 >>> 1); //prints 2147483647

since -2 = 11111111111111111111111111111110 and do an unsigned right shift, which means we shift by 1 bit with zero-extension, giving: 01111111111111111111111111111111

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值