LoginSignup
1
1

More than 5 years have passed since last update.

Byte を KB や GB に変換する Elisp コード

Posted at

1024で割った結果が1024以上である度に単位を1つ上げるという簡単な手法。

(require 'cl)
(defun convert-file-size (size)
  (loop with size-units = (list "B" "KB" "MB" "GB" "TB")
        with first-unit = (car size-units)
        with last-unit =  (car (last size-units))
        for unit in size-units
        and new_size = size then (/ new_size 1024.0)
        when (or (< new_size 1024.0) (equal unit last-unit))
        if (equal unit first-unit) return (format "%.0f%s" new_size unit)
        else return (format "%.1f%s" new_size unit)))

(convert-file-size 30)                  ; => "30B"
(convert-file-size 5000)                ; => "4.9KB"
(convert-file-size 100000000)           ; => "95.4MB"
(convert-file-size 10000000000000000.0) ; => "9094.9TB"

Byteのときは小数点以下を表示しないという処理のため少し冗長に。整数だとオーバフローする可能性があるので、その場合は少数を渡す工夫が必要。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1