Parse long to negative number

the code:

public class Main{
    public static void main(String[] a){
        long t=24*1000*3600;
        System.out.println(t*25);
        System.out.println(24*1000*3600*25);
    }
}

Fingerprints:

2160000000

-2134967296

Why?


Thanks for all the answers.

Is this the only way to use L after the number?

I tried (long)24*1000*3600*25, but this is also negative.

+3
source share
7 answers

To clearly explain this,

System.out.println(24*1000*3600*25);

The statement above is actually intliterals. To treat them as a literal long, you need a suffix with L.

System.out.println(24L*1000L*3600L*25L);

Caveat, L, I 1. I , , 1 . , L long.

+11

int, Integer.MAX_VALUE 2 ^ 31-1. - , .

. :

alt text

+18

long, int.

int : -2 ^ 31 2 ^ 31 - 1, , (int max: 2147483647 : 2160000000), int .

long:

System.out.println(24L*1000*3600*25);
+6

'l'. :

   public static void main(String[] a){
        long t=24*1000*3600;
        System.out.println(t*25);
        System.out.println(24l*1000l*3600l*25l);
    }
+3

int. 24*1000*3600*25 , Integer.MAX_VALUE, -2134967296. long L, :

System.out.println(24L*1000*3600*25);
+2

If you want to perform mathematical operations with large numerical values ​​without overflow, try the BigDecimal class.

Say I want to multiply

200,000,000 * 2,000,000,000,000,000,000 L * 20,000,000

int testValue = 200000000;
System.out.println("After Standard Multiplication = " +
                                                       testValue * 
                                                       2000000000000000000L * 
                                                       20000000);

The operation value will be -4176287866323730432, which is incorrect.

Using the BigDecimal class, you can exclude the discarded bits and get the correct result.

int testValue = 200000000;        
System.out.println("After BigDecimal Multiplication = " +
                              decimalValue.multiply(
                              BigDecimal.valueOf(2000000000000000000L).multiply(
                              BigDecimal.valueOf(testValue))));

After using BigDecimal, multiplication returns the correct result, which

80000000000000000000000000000000000

+1
source
(int)Long.valueOf("2345678901").longValue();
0
source

Source: https://habr.com/ru/post/1770069/


All Articles