Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtracting longs goes wrong

long freeSize = ((Main.maxSPace-Main.usedSpace)*1000*1000);

maxSpace = 20000
usedSpace = 8

--> freeSize = -1482836480

Why is this the result negative?

like image 633
bbholzbb Avatar asked Apr 08 '13 23:04

bbholzbb


1 Answers

Change type of maxSpace and usedSpace from int to long. If you can't do this then just change your code to something like

long freeSize = 1000L*1000*(Main.maxSPace - Main.usedSpace);

so result would be calculated as long, not int.

Now it is calculated like this

Main.maxSPace-Main.usedSpace              -> 19992
(Main.maxSPace-Main.usedSpace)*1000       -> 19992000
(Main.maxSPace-Main.usedSpace)*1000*1000L -> 19992000000

Problem here is that we are operating on integers, so result must also be integer, but max value of integer is

2147483647 so
19992000000 is out of range

so Java will take only last 32 bits of result and change it to integer

10010100111100111011011011000000000 -> 19992000000
   10100111100111011011011000000000 -> -1482836480
like image 136
Pshemo Avatar answered Sep 19 '22 13:09

Pshemo