Search code examples
javapythonmultiplication

Java multiplication of same number returns different output in Python


I am porting some Java code to Python, but for some reason, the results differ.

Java

int vi = 3997125 * 3997125;

Output: -270075495

Python

vi = 3997125 * 3997125

Output: 15977008265625

How would I accomplish the same output Java returns in Python?


Solution

  • To simulate the conversion of a python integer to 32bit integer value with overflow

    def bit32(value):
        shift =  1 << 32
        return value % shift - shift if value.bit_length() >= 32 else value
    bit32(3997125*3997125)
    

    Out:

    -270075495