1 Star 1 Fork 0

wecise/openutil

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
fmtbytes.go 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
snakebird 提交于 2025-11-14 14:37 +08:00 . fmt
package mfmt
import (
"fmt"
"regexp"
"strings"
"gitee.com/wecisecode/util/cast"
)
const (
_ = iota
KB int64 = 1 << (iota * 10)
MB
GB
TB
PB
EB
)
var reBytes = regexp.MustCompile(`^(\d+)\s*(.*)$`)
// 支持的单位:
// "K", "KB",
// "M", "MB",
// "G", "GB",
// "T", "TB",
// "P", "PB",
// "E", "EB",
// "B", "BYTE", "BYTES"
// 默认 BYTE
func ParseBytesCount(s string) int64 {
s = strings.TrimSpace(s)
if s == "" {
return 0
}
sign := int64(1)
if s[0] == '-' {
sign = -1
s = s[1:]
}
ss := reBytes.FindStringSubmatch(s)
if len(ss) < 3 {
return 0
}
unit := int64(0)
switch strings.ToUpper(ss[2]) {
case "K", "KB":
unit = KB
case "M", "MB":
unit = MB
case "G", "GB":
unit = GB
case "T", "TB":
unit = TB
case "P", "PB":
unit = PB
case "E", "EB":
unit = EB
case "", "B", "BYTE", "BYTES":
unit = 1
}
return sign * cast.ToInt64(ss[1]) * unit
}
func BytesSize(b int64) string {
if b <= -10000 {
b = (b - 512) / 1024
if b > -10000 {
return fmt.Sprintf("%dK", b)
}
b = (b - 512) / 1024
if b > -10000 {
return fmt.Sprintf("%dM", b)
}
b = (b - 512) / 1024
if b > -10000 {
return fmt.Sprintf("%dG", b)
}
b = (b - 512) / 1024
if b > -10000 {
return fmt.Sprintf("%dT", b)
}
b = (b - 512) / 1024
return fmt.Sprintf("%dP", b)
}
if b >= 10000 {
b = (b + 512) / 1024
if b < 10000 {
return fmt.Sprintf("%dK", b)
}
b = (b + 512) / 1024
if b < 10000 {
return fmt.Sprintf("%dM", b)
}
b = (b + 512) / 1024
if b < 10000 {
return fmt.Sprintf("%dG", b)
}
b = (b + 512) / 1024
if b < 10000 {
return fmt.Sprintf("%dT", b)
}
b = (b + 512) / 1024
return fmt.Sprintf("%dP", b)
}
return fmt.Sprintf("%d", b)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/wecisecode/util.git
git@gitee.com:wecisecode/util.git
wecisecode
util
openutil
v0.8.6

搜索帮助