Skip to content

Instantly share code, notes, and snippets.

@HoweChen
Created December 8, 2019 08:03
Show Gist options
  • Save HoweChen/203de90210f2425978a18194a6c1b780 to your computer and use it in GitHub Desktop.
Save HoweChen/203de90210f2425978a18194a6c1b780 to your computer and use it in GitHub Desktop.
[文件大小转换byte to kb, mb, gb, pb, eb, zb ] #Java
public static strictfp String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
long absBytes = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
if (absBytes < unit) return bytes + " B";
int exp = (int) (Math.log(absBytes) / Math.log(unit));
long th = (long) (Math.pow(unit, exp) * (unit - 0.05));
if (exp < 6 && absBytes >= th - ((th & 0xfff) == 0xd00 ? 52 : 0)) exp++;
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
if (exp > 4) {
bytes /= unit;
exp -= 1;
}
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment