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

前端 未结 5 1925
忘掉有多难
忘掉有多难 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:22

    According to the documentation Math.pow will promote both of its arguments to double and return double. Obviously when the returned result is double and you cast it to int you'll get only the highest 32 bits and the rest will be truncated - hence you always get the (int) Math.pow(2,x); value. When you do bitshift you always work with ints and hence an overflow occurs.

提交回复
热议问题