如何在Go中生成字符串的哈希值?

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

How to generate hash number of a string in Go?

问题

例如:

  1. hash("HelloWorld") = 1234567

是否有任何内置函数可以做到这一点?

谢谢。

英文:

For example:

  1. hash("HelloWorld") = 1234567

Is there any built-in function could do this ?

Thanks.

答案1

得分: 132

hash 包对此很有帮助。请注意,它是对特定哈希实现的抽象。一些现成的实现可以在 子目录 中找到。

示例:

  1. package main
  2. import (
  3. "fmt"
  4. "hash/fnv"
  5. )
  6. func hash(s string) uint32 {
  7. h := fnv.New32a()
  8. h.Write([]byte(s))
  9. return h.Sum32()
  10. }
  11. func main() {
  12. fmt.Println(hash("HelloWorld"))
  13. fmt.Println(hash("HelloWorld."))
  14. }

(也可以在 这里 查看)


输出:

  1. 926844193
  2. 107706013
英文:

The hash package is helpful for this. Note it's an abstraction over specific hash implementations. Some ready made are found in the package subdirectories.

Example:

  1. package main
  2. import (
  3. "fmt"
  4. "hash/fnv"
  5. )
  6. func hash(s string) uint32 {
  7. h := fnv.New32a()
  8. h.Write([]byte(s))
  9. return h.Sum32()
  10. }
  11. func main() {
  12. fmt.Println(hash("HelloWorld"))
  13. fmt.Println(hash("HelloWorld."))
  14. }

(Also here)


Output:

  1. 926844193
  2. 107706013

答案2

得分: 9

这里是一个你可以用来生成哈希数的函数:

  1. // 使用fnv32a算法进行FNV32a哈希
  2. func FNV32a(text string) uint32 {
  3. algorithm := fnv.New32a()
  4. algorithm.Write([]byte(text))
  5. return algorithm.Sum32()
  6. }

我在这里组合了一组实用的哈希函数:https://github.com/shomali11/util

你会找到FNV32FNV32aFNV64FNV64aMD5SHA1SHA256SHA512

英文:

Here is a function you could use to generate a hash number:

  1. // FNV32a hashes using fnv32a algorithm
  2. func FNV32a(text string) uint32 {
  3. algorithm := fnv.New32a()
  4. algorithm.Write([]byte(text))
  5. return algorithm.Sum32()
  6. }

I put together a group of those utility hash functions here: https://github.com/shomali11/util

You will find FNV32, FNV32a, FNV64, FNV64a, MD5, SHA1, SHA256 and SHA512

huangapple
  • 本文由 发表于 2012年11月27日 18:46:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/13582519.html
匿名

发表评论

匿名网友

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

确定