go 传入Byte 输出输出HumanSize

本文介绍如何通过HumanSizeOutput接口将Byte大小转换为易于理解的Gib、Mib、Kib或Bit,提高数据展示的可读性。通过示例代码和使用方法展示了这个实用工具在工作中简化单位转换的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工作中,常常会有一些场景 获取到的结果单位是Byte,但是直接展示又不适合读者看,因此写了一个Human的接口,方便使用。
代码实现如下:

package output

type HumanOutput struct {
	ByteSize int64
}

type HumanSizeOutput interface {
	HumanByteSize() (h int64, s string)
}

func NewHumanSizeMessage(s int64) (humansize int64,Unit string){
	var msg HumanSizeOutput
	msg = NewHumanOutput(s)
	humansize , Unit = msg.HumanByteSize()
	return
}

func (HumanOutput *HumanOutput) HumanByteSize() (h int64, s string) {
	const kb = 1024
	const mb = 1024 * kb
	const gb = 1024 * mb
	var humanSize int64
	var humanUnit string
	if HumanOutput.ByteSize > gb {
		humanSize = HumanOutput.ByteSize / gb
		humanUnit = "Gib"
	} else if HumanOutput.ByteSize > mb {
		humanSize = HumanOutput.ByteSize / mb
		humanUnit = "Mib"
	} else if HumanOutput.ByteSize > kb {
		humanSize = HumanOutput.ByteSize / kb
		humanUnit = "Kib"
	} else {
		humanSize = HumanOutput.ByteSize
		humanUnit = "Bit"
	}
	return humanSize, humanUnit
}

func NewHumanOutput(bytesize int64) *HumanOutput {
	return &HumanOutput{
		ByteSize: bytesize,
	}
}

使用方法也比较简单

bytesize:=12345678910
size, unit := output.NewHumanSizeMessage(int64(bytesize))
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值