Subtracting lengths incorrectly

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

-> freeSize = -1482836480

Why is this a negative result?

+7
source share
4 answers

Change the type of maxSpace and usedSpace from int to long . If you cannot do this, simply change the code to something like

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

therefore, the result will be calculated as long , not int .

Now it computes like this:

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

The problem is that we are working with integers, so the result should also be integer, but the maximum integer value is

 2147483647 so 19992000000 is out of range 

therefore Java will only take the last 32 bits of the result and change it to an integer

 10010100111100111011011011000000000 -> 19992000000 10100111100111011011011000000000 -> -1482836480 
+5
source

maxSpace and usedSpace are declared as int, so all arithmetic is done using int. Only when you assign the result to freeSize is it discarded to a long one, but the overflow happened before that.

Try replacing the number 1000 with 1000L to force the earlier:

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

You are probably getting a negative number because maxSpace and usedSpace are ints. 20000 - 8 = 19992 , 19992 * 1000000 = 19992000000 , which is less than Long.MAX_VALUE (2 63 - 1), but it is larger than Integer.MAX_VALUE (2 31 - 1). 19992000000 - Integer.MAX_VALUE = 17844516353 , which is still out of bounds for the int value. You must allow maxSpace and usedSpace be long.

+3
source

When maxSpace and usedSpace are of type int, you will get a negative value due to type overflow. Use long instead of the two variables maxSpace and usedSpace. In addition, if you cannot change the types of Main properties, you can change your code to:

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

All Articles