Java parse bytes number over 39.4 GB on a long var bug
I have an app that get ftp disk space. so space given by a number that present how many bytes.
the problem is when i got space over 39.4 GB i can just store 39.4*1024开发者_JS百科*1024*1024 in a long or double var. so if you have 50 GB it just show you 39.4. whats the solution?
long
can store much larger values -- so there must be something specific in your code. I guessed at what your code is doing, see if this looks familiar:
class Out {
public static void main(String args[]) {
long l = 40L * 1024 * 1024 * 1024;
double d = 40.0 * 1024 * 1024 * 1024;
System.out.println("long l: " + l + " double d: " + d + "\n");
return;
}
}
$ vim Out.java ; javac Out.java ; java Out
long l: 42949672960 double d: 4.294967296E10
Note that I had to multiply 40L
rather than just 40
-- if all integers are given as literal integers, without specific L
long
annotations, then Java will interpret the entire expression as an int
. When testing with and without the L
(and multiplying by just 1024 * 1024 * 102
, building up to confirming my hypothesis), I found the differences entertaining:
$ vim Out.java ; javac Out.java ; java Out # with only '40'
long l: -16777216 double d: 4.294967296E10
$ vim Out.java ; javac Out.java ; java Out # with '40L'
long l: 4278190080 double d: 4.294967296E10
I hope this helps explain why it is important to specify the types of literal data types in the code.
Here is the solution for storing an amount greater than 39.4 GB:
final long kb = 1024L;
final long mb = 1024L*kb;
final long gb = 1024L*mb;
long solution = 42L * gb; // > 39.4 GB in a long
See if BigInteger class helps you with your problem
http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html
EDIT:
Actually as others already mentioned, long value will be able to hold a really big value, it can hold far more than 40gb as a number value
long
can record 8 Exa-bytes which is 8 * 1024 * 1024 * 1024 GB (minus one byte ;)
精彩评论