func main() {
//数据准备
src := []byte("abcdef") // 准备数据
dst := make([]byte, hex.EncodedLen(len(src))) // 计算转换为16进制后的长度
//加密
hex.Encode(dst, src) // 转码
fmt.Printf("%s\n", dst) // 打印 616263646566,a的ascii码为97,97转换为16进制为61,后面的bcdef同理
//直接加密
fmt.Println(hex.EncodeToString(src)) // 直接将byte切片转为字符串,打印 616263646566
//解密
src = make([]byte, hex.DecodedLen(len(dst))) // 准备容器
hex.Decode(src, dst) // 解码
fmt.Printf("%s\n", src) // 打印abcdef
// 直接解码字符串
b, _ := hex.DecodeString(string(dst))
fmt.Printf("%s\n", b) // 打印abcdef
}
encoding/hex
最新推荐文章于 2026-03-30 04:30:07 发布
本文展示了如何在Go语言中进行十六进制的编码与解码操作。通过`hex.Encode`和`hex.Decode`函数,可以轻松地将字节切片转换为十六进制字符串,并将十六进制字符串还原回原始数据。示例代码详细演示了这个过程,对于理解Go语言的数据转换非常有帮助。
2292

被折叠的 条评论
为什么被折叠?



