74

For example:

hash("HelloWorld") = 1234567

Is there any built-in function could do this ?

Thanks.

2
  • 2
    Not Go specific but interesting and related: stackoverflow.com/a/107657/532430 Commented Nov 27, 2012 at 21:11
  • 1
    that's known as prehash, theoretically. Commented May 15, 2016 at 10:12

2 Answers 2

141

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
Sign up to request clarification or add additional context in comments.

7 Comments

Also, it's possible to use single instance and Write/Reset, instead of creating New32a every time. I don't know how much it's cost. For example: play.golang.org/p/aUeNBo755g
Are these hashes unique? can i use it as a unique identifier?
These hashes are not very unique. The chances of two different strings matching the same uint32 are approximately 1 to 4 billion. I would not use it for uniqueness. Here is an example which may prove more useful: every task has a unique "string", and I would like to uniformly distribute the tasks between 50 queues. I would do (with the above function) hash("HelloWorld") % 50.
@iwind Every hash function into a smaller space (like arbitrary-length string into uint32 here) is guaranteed to have collisions so "I found one specific collision" is not an argument for whether a method is good or bad. If you analyzed the method and found a high collision rate or nonuniform distribution or some other meaningful flaw that would be a compelling argument, but I imagine such analyses already exist for FNV.
@IvanBlack I wonder about the concurrency and race condition issues when using that same New32a instance in each call to getHash. In my mind, two simultaneous getHash function calls could interleave in a way that results in one of them Resetting the other's Write before it does a Sum call, giving a result you wouldn't want.
|
10

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.