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

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

How to generate hash number of a string in Go?

问题

例如:

hash("HelloWorld") = 1234567

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

谢谢。

英文:

For example:

hash("HelloWorld") = 1234567

Is there any built-in function could do this ?

Thanks.

答案1

得分: 132

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

示例:

package main

import (
        "fmt"
        "hash/fnv"
)

func hash(s string) uint32 {
        h := fnv.New32a()
        h.Write([]byte(s))
        return h.Sum32()
}

func main() {
        fmt.Println(hash("HelloWorld"))
        fmt.Println(hash("HelloWorld."))
}

(也可以在 这里 查看)


输出:

926844193
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:

package main

import (
        "fmt"
        "hash/fnv"
)

func hash(s string) uint32 {
        h := fnv.New32a()
        h.Write([]byte(s))
        return h.Sum32()
}

func main() {
        fmt.Println(hash("HelloWorld"))
        fmt.Println(hash("HelloWorld."))
}

(Also here)


Output:

926844193
107706013

答案2

得分: 9

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

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

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

你会找到FNV32FNV32aFNV64FNV64aMD5SHA1SHA256SHA512

英文:

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

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

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:

确定