bytes.go 577 B

123456789101112131415161718192021222324252627282930313233
  1. package bytes
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. var (
  7. sfx = "B"
  8. )
  9. // BinaryPrefix sets binary prefix as specified by ICE standard. For example, 13.23 MiB.
  10. func BinaryPrefix(on bool) {
  11. if on {
  12. sfx = "iB"
  13. } else {
  14. sfx = "B"
  15. }
  16. }
  17. // Bytes formats bytes into string. For example, 1024 returns 1 KB
  18. func Format(b uint64) string {
  19. n := float64(b)
  20. unit := float64(1024)
  21. if n < unit {
  22. return fmt.Sprintf("%.0f B", n)
  23. } else {
  24. e := math.Floor(math.Log(n) / math.Log(unit))
  25. pfx := "KMGTPE"[uint8(e)-1]
  26. return fmt.Sprintf("%.02f %c%s", n/math.Pow(unit, e), pfx, sfx)
  27. }
  28. }