I have created a method that detect the best prefix for it. Example, if you enter 1024, it should return string: "1 kb".
But it convert wrong is some cases.
Code:private static final long B_MIN = 0x00;
private static final long B_MAX = 0x3FF;
private static final long KB_MIN = 0x400;
private static final long KB_MAX = 0xFFFFF;
private static final long MB_MIN = 0x100000;
private static final long MB_MAX = 0x3FFFFFFF;
private static final long GB_MIN = 0x40000000;
private static final long GB_MAX = 0xFFFFFFFFFFL;
private static final long TB_MIN = 0x10000000000L;
private static final long TB_MAX = 0x4000000000000L;
private static strictfp String getSizeInfo (long size) //Arg in bytes
{
String info = null;
if (size >= B_MIN && size <= B_MAX)
info = size + " b";
else if (size >= KB_MIN && size <= KB_MAX)
info = (size / 1000) + " kb";
else if (size >= MB_MIN && size <= MB_MAX)
info = (size / 1000000) + " mb";
else if (size >= GB_MIN && size <= GB_MAX)
{
double d = (double)Math.round(((double) size / 1000000000L) * 100) / 100;
info = d + " gb";
}
else if (size >= TB_MIN && size <= TB_MAX)
info = (double) (size / 1000000000000L) + " tb";
else
throw new IllegalArgumentException (Long.toString (size));
return info;
}
public static void main (String[] args)
{
System.out.println(getSizeInfo (5));
System.out.println(getSizeInfo (1000));
System.out.println(getSizeInfo (1024));
System.out.println(getSizeInfo (50000));
System.out.println(getSizeInfo (KB_MAX));
System.out.println(getSizeInfo (MB_MIN));
System.out.println(getSizeInfo (MB_MAX));
System.out.println(getSizeInfo (GB_MIN));
System.out.println(getSizeInfo (GB_MAX));
System.out.println(getSizeInfo (TB_MIN));
System.out.println(getSizeInfo (TB_MAX));
}
I am very suspicious about this method. Is it really wrong or am I to confused?Code:5 b
1000 b
1 kb
50 kb
1048 kb
1 mb
1073 mb
1.07 gb <- Shouldnt this one be 1.0?
1099.51 gb - This one is wrong to
1.0 tb
1125.0 tb
