Why does bit-wise shift left return different results in Python and Java?

前端 未结 3 1945
遇见更好的自我
遇见更好的自我 2021-02-19 14:05

I\'m trying to port some functionality from a Java app to Python.

In Java,

System.out.println(155 << 24);

Returns: -1694498816

3条回答
  •  伪装坚强ぢ
    2021-02-19 14:26

    Java has 32-bit fixed width integers, so 155 << 24 shifts the uppermost set bit of 155 (which is bit 7, counting bits from zero, because 155 is greater than 27 but less than 28) into the sign bit (bit 31) and you end up with a negative number.

    Python has arbitrary-precision integers, so 155 << 24 is numerically equal to the positive number 155 × 224

提交回复
热议问题