Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Java processes for overflow integers [duplicate]

Now signed_int max value is 2,147,483,647 i.e. 2^31 and 1 bit is sign bit, so

when I run long a = 2,147,483,647 + 1;

It gives a = -2,147,483,648 as answer.. This hold good. But, 24*60*60*1000*1000 = 86400000000 (actually)... In java, 24*60*60*1000*1000 it equals to 500654080.. I understand that it is because of overflow in integer, but what processing made this value come, What logic was used to get that number by Java. I also refered here.

like image 468
Gru Avatar asked Jul 02 '13 09:07

Gru


1 Answers

Multiplication is executed from left to right like this

    int x = 24 * 60;    
    x = x * 60;     
    x = x * 1000; 
    x = x * 1000;

first 3 operations produce 86400000 which still fits into Integer.MAX_VALUE. But the last operation produces 86400000000 which is 0x141dd76000 in hex. Bytes above 4 are truncated and we get 0x1dd76000. If we print it

System.out.println(0x1dd76000);

the result will be

500654080
like image 161
Evgeniy Dorofeev Avatar answered Oct 04 '22 20:10

Evgeniy Dorofeev