问题描述
为什么以下两个操作在Java中为 x = 31
或 32
产生不同的结果,但结果相同对于 x = 3
?
Why do the following two operations yield different results in Java for x = 31
or 32
but the same results for x=3
?
int x=3;
int b = (int) Math.pow(2,x);
int c = 1<<x;
结果:
x=32: b=2147483647; c=1;
x=31: b=2147483647; c=-2147483648;
x=3: b=8 ; c=8
推荐答案
有多个问题在起作用:
-
int
只能存储-2147483648之间的值
和2147483647
。 -
1<< x
仅的最低五位。因此,1<<根据定义,32
与1<< 0
。 - 移位操作在;这解释了为什么
1<< 31
是否定的。 -
Math.pow(2,32)
返回double
。 -
(int)(d)
,其中d
是double
大于2147483647
返回2147483647
()的可表示值。
- An
int
can only store values between-2147483648
and2147483647
. 1 << x
only uses the lowest five bits ofx
. Thus,1 << 32
is by definition the same as1 << 0
.- Shift operations are performed on the two's-complement integer representation of the value of the left operand; this explains why
1 << 31
is negative. Math.pow(2, 32)
returns adouble
.(int)(d)
, whered
is adouble
greater than2147483647
returns2147483647
("the largest representable value of typeint
").
这是什么面试问题确实显示(int)Math.pow(2,x)
和 1<< x
与 0
之外的 x
的值不等效... 30
范围。
What this interview question does is show that (int)Math.pow(2, x)
and 1 << x
are not equivalent for values of x
outside the 0
...30
range.
PS或许有趣的是,使用 long
代替 int
(以及 1L
代替 1
)会给出另一组与其他两个不同的结果。即使最终结果转换为 int
,这也成立。
P.S. It is perhaps interesting to note that using long
in place of int
(and 1L
in place of 1
) would give yet another set of results different from the other two. This holds even if the final results are converted to int
.
这篇关于(int)Math.pow(2,x)和1<< x的Java结果不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!