Java results differ for (int)Math.pow(2,x) and 1<<x

前端 未结 5 1924
忘掉有多难
忘掉有多难 2020-12-31 17:21

Why do the following two operations yield different results in Java for x = 31 or 32 but the same results for x=3?

int         


        
5条回答
  •  执笔经年
    2020-12-31 17:27

    There are multiple issues at play:

    • An int can only store values between -2147483648 and 2147483647.
    • 1 << x only uses the lowest five bits of x. Thus, 1 << 32 is by definition the same as 1 << 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 a double.
    • (int)(d), where d is a double greater than 2147483647 returns 2147483647 ("the largest representable value of type int").

    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.

    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.

提交回复
热议问题