比如1024 byte,格式化为1Kb,1024kb格式化为1Mb。
1public static String humanReadableByteCountBin(long bytes) {
2 long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
3 if (absB < 1024) {
4 return bytes + " B";
5 }
6 long value = absB;
7 CharacterIterator ci = new StringCharacterIterator("KMGTPE");
8 for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) {
9 value >>= 10;
10 ci.next();
11 }
12 value *= Long.signum(bytes);
13 return String.format("%.1f %ciB", value / 1024.0, ci.current());
14}
内容