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

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

    int is 32 bits in size and since it is signed (by default), the first bit is used for the sign. When you shift left 31 bits, you get the Two's Compliment, which is -(2^32). When you shift left 32 bits, it just loops all the way back around to 1. If you were to do this shifting with longs instead of ints, you would get the answers you expect (that is until you shift 63+ bits).

提交回复
热议问题