golang md5 结果类型

本文介绍了使用Golang实现MD5加密的过程,并演示了如何正确转换MD5结果为字符串形式。文章通过具体代码示例解释了为何不能直接将MD5结果转换为string类型,以及如何利用encoding/hex包将字节切片转换为十六进制字符串。

golang  md5 结果类型

 

  1 package main
  2
  3 import (
  4         "crypto/md5"
  5         "encoding/hex"
  6         "fmt"
  7 )
  8
  9 func main() {
 10         data := []byte("testing")
 11         b := md5.Sum(data)
 12         fmt.Println(string(b)) //错误,不能直接转 string 
 13 //      fmt.Println(hex.EncodeToString(b[:]))
 14 //      fmt.Println(b[:])
 15 }
# command-line-arguments
GoProjcet/src/exercise/test_md5.go:12: cannot convert b (type [16]byte) to type string

 

 

Note:

Also note that converting a "random" slice of bytes to a string is most likely not what you want because a "random" slice of bytes may not be a valid UTF-8 byte sequence.

Instead use the encoding/hex package to convert the result to a hex string like this:

fmt.Println(hex.EncodeToString(b[:]))


  1 package main
  2
  3 import (
  4         "crypto/md5"
  5         "encoding/hex"
  6         "fmt"
  7 )
  8
  9 func main() {
 10         data := []byte("testing")
 11         b := md5.Sum(data)
 12 //      fmt.Println(string(b))
 13         fmt.Println(hex.EncodeToString(b[:]))
 14         fmt.Println(b[:])
 15 }
ae2b1fca515949e5d54fb22b8ed95575
[174 43 31 202 81 89 73 229 213 79 178 43 142 217 85 117]

 



转载于:https://www.cnblogs.com/DillGao/p/7443251.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值