英文:
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 'Ӿ��]앿��N��' 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("%x", sum)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论