Skip to content

Instantly share code, notes, and snippets.

@youz
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save youz/423a5730dc7fb9951ef4 to your computer and use it in GitHub Desktop.
Save youz/423a5730dc7fb9951ef4 to your computer and use it in GitHub Desktop.
format-byte-size
;; ref. http://msdn.microsoft.com/en-us/library/windows/desktop/bb759975(v=vs.85).aspx
(defun format-byte-size (n)
(labels ((rec (n units)
(cond ((null units))
((< n 10)
(format nil "~,2f~a" n (car units)))
((< n 100)
(format nil "~2,1f~a" n (car units)))
((< n 1000)
(format nil "~d~a" (floor n) (car units)))
(t
(rec (/ n 1024) (cdr units))))))
(rec n '("" Ki Mi Gi Ti Pi Ei Zi Yi))))
@youz
Copy link
Author

youz commented Sep 5, 2014

StrFormatByteSizeA を使った場合

;;; xyzzy lisp
(c:*define-dll-entry c::PSTR
  StrFormatByteSize
  (c::DWORD
   c::PSTR
   c::u_int)
  "Shlwapi" "StrFormatByteSizeA")

(defun winapi-format-byte-size (n)
  (let ((c (si:make-chunk nil 50)))
    (when (> (StrFormatByteSize n c 50) 0)
      (si:unpack-string c 0))))

(winapi-format-byte-size 1023)
; => "1023 バイト"

(winapi-format-byte-size (* 1024 999))
; => "999 KB"

(winapi-format-byte-size (* 1024 1000))
; => "0.97 MB"

(winapi-format-byte-size (* 1024 1024))
; => "1.00 MB"

(winapi-format-byte-size (expt 2 31))
; => "2.00 GB"

(winapi-format-byte-size (expt 2 32))
; => "0 バイト"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment