移位操作不返回预期结果 [英] bit shift operation does not return expected result

查看:148
本文介绍了移位操作不返回预期结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Java的回报的 -2147483648 的时候我位移位的 1 LT;< 63 的?

预期的结果是9 223 372 036 854 775 808,与Wolfram Alpha的,我的计算器测试。

我测试:


  

System.out.print((长)(1 LT;≤(63)));



解决方案

还有需要注意的行一个重要的事情

  System.out.print((长)(1 LT;≤(63)));

您先(1 LT;< 63)然后的你投来长。其结果是,你实际上是左移的整数,所以长投没有任何效果。这就是为什么转向63位向左给出了最小的整数,而不是分钟长。

但是,还有另一个更重要的一点。 Java的多头总是签署,因此,即使行

  System.out.print(1L<< 63);

将得到负数。根据2的补每当最左边的位是1的数目是负的。

您却不能再​​present 2号 63 =在Java原始类型9223372036854775808,因为这个数字比最大长做大,是最大的基本类型。您可以重新present这个数字为的BigInteger ,虽然。你甚至可以通过63与code

左移生成它

  BigInteger.ONE.shiftLeft(63)

Why does Java return -2147483648 when I bit shift 1 << 63 ?

The expected result is 9 223 372 036 854 775 808, tested with Wolfram Alpha and my calculator..

I tested:

System.out.print((long)(1 << (63)));

解决方案

There's an important thing to note about the line

System.out.print((long)(1 << (63)));

You first take (1 << 63), and then you cast to long. As a result, you are actually left-shifting in integers, so the long cast doesn't have any effect. That's why shifting 63 bits left gives the min integer rather than the min long.

But there's another, more important point. Java longs are always signed, so even the line

System.out.print(1L << 63);

would give a negative number. Under two's complement, whenever the leftmost bit is a 1 the number is negative.

You actually cannot represent the number 263 = 9223372036854775808 in a Java primitive type, because that number is bigger than the maximum long, and long is the largest primitive type. You can represent this number as a BigInteger, though. You can even generate it via a left-shift by 63 with the code

BigInteger.ONE.shiftLeft(63)

这篇关于移位操作不返回预期结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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