bytes.go 723 B

123456789101112131415161718192021222324252627282930313233343536
  1. package bytes
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. )
  7. // Format formats bytes to string. For example, 1024 returns 1 KB
  8. func Format(b uint64) string {
  9. return format(float64(b), false)
  10. }
  11. // FormatBin formats bytes to string as specified by ICE standard. For example,
  12. // 13.23 MiB.
  13. func FormatBin(b uint64) string {
  14. return format(float64(b), true)
  15. }
  16. func format(b float64, bin bool) string {
  17. unit := float64(1000)
  18. if bin {
  19. unit = 1024
  20. }
  21. if b < unit {
  22. return fmt.Sprintf("%.0f B", b)
  23. } else {
  24. exp := math.Floor(math.Log(b) / math.Log(unit))
  25. pfx := new(bytes.Buffer)
  26. pfx.WriteByte("KMGTPE"[uint8(exp)-1])
  27. if bin {
  28. pfx.WriteString("i")
  29. }
  30. return fmt.Sprintf("%.02f %sB", b/math.Pow(unit, exp), pfx)
  31. }
  32. }