如何在Go中获取十六进制编码的md5哈希值

huangapple go评论82阅读模式
英文:

How to get hex-encoded md5 hash in Go

问题

我正在尝试在Go中获取文件的md5哈希值,如下所示:

running_hash := md5.New(); // 类型为hash.Hash
running_hash.Write(data);  // data是[]byte
sum := running_hash.Sum(); // 根据编译器,返回[]uint8

但是当我尝试获取哈希值的字符串表示(http://golang.org/pkg/hash/),通过以下方式:

sumstring := string(sum);  // 返回'Ӿ��]앿��N��'或类似的结果

当哈希值应该是d3be9e835dec95bfbef34ebe1fbf03da时,我得到了相同类型的无意义结果,只是字符不同,当我尝试逐字节转换时也是如此。

我应该如何获取哈希值的字符串表示?

英文:

I'm trying to get the md5 hash of a file in Go, like thus:

running_hash := md5.New(); // type hash.Hash
running_hash.Write(data);  // data is []byte
sum := running_hash.Sum(); // []uint8 according to the compiler

But when I try to get the string of the hash's 'sum' (<http://golang.org/pkg/hash/>), via

sumstring := string(sum);  // returns &#39;Ӿ��]앿��N��&#39; or similar

when the hash is supposed to be d3be9e835dec95bfbef34ebe1fbf03da. I get the same sort of nonsense, only with different characters, when I try to convert on a byte-by-byte basis.

How am I meant to get the hash's string?

答案1

得分: 17

基本上,你已经有了二进制数据,但是看起来你期望的是十六进制。可以查看hex包中的转换函数,特别是EncodeToString。我不是Go程序员,但我认为如果你只是将sum传递给hex.EncodeToString,你会得到你期望的答案。

英文:

Basically, you've got the binary data but it looks like you're expecting hex. Have a look at the hex package for conversion routines, especially EncodeToString. I'm not a Go programmer, but I think if you just pass sum into hex.EncodeToString, you'll get the answer you expected.

答案2

得分: 9

alternately, you can get the hex representation of a string or byte slice easily using fmt.Sprintf("%x", sum)

英文:

alternately, you can get the hex representation of a string or byte slice easily using fmt.Sprintf(&quot;%x&quot;, sum)

huangapple
  • 本文由 发表于 2011年11月3日 07:23:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/7988543.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定