简体   繁体   中英

Java sum 2 negative numbers

I'm trying to convert a function in java to pl/pgsql, and one problem that I found is when I'm trying to sum 2 negative numbers, and a get a positive number, more specifically :

public void sum(){
    int n1 = -1808642602;
    int n2 = -904321301;
    System.out.println(n1 + n2);// result is 1582003393
}

And in pl/pgsql I get an integer out of range error, and if I change the variables type to bigint i get a normal sum of 2 negative numbers, that is -2712963903, instead of 1582003393

How do I do to pl/pgsql get the same result without printing an integer out of range error?

This happens because the Java int underflows and doesn't tell you.

To get the answer you are looking for in pl, you need to use bigint. Then detect the case when the result is less than Java Integer.MIN_INT (-2^31), which is the case where Java will give a positive result. To get what Java would give you, add 2^32.

long溢出int尝试相同的事情,它应该可以工作。

It's overflowing, because the result is too big for an int. Use long instead.

Java sums them as 32 bit signed integers, which wrap at -2 31 . Have you tried a 64 bit long instead?

That valid rand of int in Java is -2,147,483,648 to 2,147,483,647 ( -2^31 - 2^31-1 ).

You are causing an Integer underflow. You should use a type long instead of int which ranges from -2^63 to 2^63-1

Java treats those 2 numbers as signed integers. Basically the scope for singed integers is -2,147,483,648 to 2,147,483,647 (-2^31 - 2^31-1). Hence the sum of those to values is -2712963903 which is less than the the minimum -2^31 so underflows and then wraps around by doing 2^32 - 2712963903 which gives you the signed int 1582003393.

尝试使用不会在这种情况下溢出的long整数(但对于足够大的数字)

System.out.println((long) n1 + n2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM