java - subtracting longs goes wrong -


long freesize = ((main.maxspace-main.usedspace)*1000*1000);  maxspace = 20000 usedspace = 8 

--> freesize = -1482836480

why result negative?

change type of maxspace , usedspace int long. if can't change code

long freesize = 1000l*1000*(main.maxspace - main.usedspace); 

so result calculated long, not int.

now calculated

main.maxspace-main.usedspace              -> 19992 (main.maxspace-main.usedspace)*1000       -> 19992000 (main.maxspace-main.usedspace)*1000*1000l -> 19992000000 

problem here operating on integers, result must integer, max value of integer

2147483647 19992000000 out of range 

so java take last 32 bits of result , change integer

10010100111100111011011011000000000 -> 19992000000    10100111100111011011011000000000 -> -1482836480 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -