Go语言:字节数转换为人类可读字符串(human readable)

Here’s how to convert 1000 to "1 kB"1000000 to "1 MB" etc.

func ByteCountDecimal(b int64) string {
        const unit = 1000
        if b < unit {
                return fmt.Sprintf("%d B", b)
        }
        div, exp := int64(unit), 0
        for n := b / unit; n >= unit; n /= unit {
                div *= unit
                exp++
        }
        return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "kMGTPE"[exp])
}

func ByteCountBinary(b int64) string {
        const unit = 1024
        if b < unit {
                return fmt.Sprintf("%d B", b)
        }
        div, exp := int64(unit), 0
        for n := b / unit; n >= unit; n /= unit {
                div *= unit
                exp++
        }
        return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
}

Example input/output:

           Input     Decimal (SI)     Binary (IEC)
               0            "0 B"            "0 B"
              27           "27 B"           "27 B"
             999          "999 B"          "999 B"
            1000         "1.0 kB"         "1000 B"
            1023         "1.0 kB"         "1023 B"
            1024         "1.0 kB"        "1.0 KiB"
            1728         "1.7 kB"        "1.7 KiB"
   1855425871872         "1.9 TB"        "1.7 TiB"
   math.MaxInt64         "9.2 EB"        "8.0 EiB
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值