sw1nn

Adventures. Stories. Code.

Human Readable Size

| Comments

I stumbled on this answer on stackoverflow to the question ‘how to convert byte size to human readable form in java.’

The code looks like this:

1
2
3
4
5
6
7
    public static String humanReadableByteCount(long bytes, boolean si) {
        int unit = si ? 1000 : 1024;
        if (bytes < unit) return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }

The answer is pretty sweet in java. I wondered what it might look like in clojure….

1
2
3
4
5
6
7
(defn bytes->human-readable [bytes & [si?]]
  (let [unit (if si? 1000 1024)]
    (if (< bytes unit) (str bytes " B")
         (let [exp (int  (/ (Math/log bytes)
                            (Math/log unit)))
               pre (str (nth (if si? "kMGTPE" "KMGTPE") (dec exp)) (if-not si? "i" ))]
           (format "%.1f %sB" (/ bytes (Math/pow unit exp)) pre)))))

Actually surprisingly similar. The difference is that the clojure code looks familiar whereas the java code looks quite optimized. Simply put in clojure you will tend to write short meaningful code, whereas in java you will have to work hard at it….

Comments